You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不使用正则表达式的情况下忽略空格执行PHP explode操作

解决方案

要在不使用正则的前提下,忽略字符串中的空格执行分割操作,这里提供两种可行方法:

方法一:移除空格后分割

这种方法简洁高效,先移除原字符串和分割符中的所有空格,再用explode执行分割即可:

<?php
$text = "A Beauti f u l Bird";
$delimiter = "Beautiful";

// 移除原字符串中的所有空格
$textNoSpaces = str_replace(' ', '', $text);
// 移除分割符中的空格(通用处理,适配分割符带空格的场景)
$delimiterNoSpaces = str_replace(' ', '', $delimiter);

$arr = explode($delimiterNoSpaces, $textNoSpaces);
echo $arr[0]; // 输出:A
?>

方法二:手动匹配分割符(保留原空格结构)

如果需要保留原字符串的空格结构,仅在匹配分割符时忽略空格,可以手动遍历字符串逐个字符匹配:

<?php
$text = "A Beauti f u l Bird";
$delimiter = "Beautiful";

$textPos = 0;
$delimPos = 0;
$textLen = strlen($text);
$delimLen = strlen($delimiter);

// 遍历字符串,忽略空格匹配分割符
while ($textPos < $textLen && $delimPos < $delimLen) {
    // 跳过原字符串中的空格
    while ($textPos < $textLen && $text[$textPos] === ' ') {
        $textPos++;
    }
    // 跳过分割符中的空格
    while ($delimPos < $delimLen && $delimiter[$delimPos] === ' ') {
        $delimPos++;
    }

    if ($textPos >= $textLen || $delimPos >= $delimLen) {
        break;
    }

    // 字符匹配则同时推进索引
    if ($text[$textPos] === $delimiter[$delimPos]) {
        $textPos++;
        $delimPos++;
    } else {
        // 不匹配则重置分割符索引,继续遍历原字符串
        $delimPos = 0;
        $textPos++;
    }
}

// 若分割符完全匹配,截取匹配位置前的内容并去除末尾空格
if ($delimPos === $delimLen) {
    $result = trim(substr($text, 0, $textPos - $delimLen));
} else {
    $result = $text;
}

echo $result; // 输出:A
?>

内容的提问来源于stack exchange,提问作者Asif Iqbal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:39:40