PHP 数组作为起止边界提取字符串时终止词匹配顺序异常问题
指定字符串区间提取函数的逻辑修复方案
现有函数的核心缺陷
原函数实现存在三个直接导致匹配结果偏差的问题:
- 终止词匹配顺序完全受传入数组的元素排列影响,不会自动识别文本中实际最先出现的终止词位置
- 遍历终止词数组时,每次计算的截取长度会直接覆盖之前的结果,没有取所有有效匹配中位置最靠前的终点
- 缺少边界场景判断:如果匹配不到对应字符串,会出现未定义变量、运算类型错误的问题,且不兼容起始词、终止词为数组的传入形式
原问题对应的异常表现:
// 原测试代码 $array_a = ['the', 'amen']; // 起始匹配候选 $array_b = [',', '.']; // 终止匹配候选 $str = "Hello, the world. Then, it is over.";
- 预期正确结果:
the world. - 旧函数实际返回:
the world. Then,
修复后需要实现的匹配规则
完全忽略终止词在数组中的排列顺序,按照文本实际出现顺序匹配:
- 从所有候选起始词中,找到文本里最先出现的那个,确定内容区间的起点
- 从起点位置向后扫描,对所有候选终止词分别计算第一次出现的位置
- 选取所有终止词里位置最靠前的那个作为区间终点,截取两个位置之间的内容返回
修改后的完整函数代码
function string_between($str, $starting_word, $ending_word) { // 处理起始词匹配:兼容单个字符串/数组形式,取最早出现的起始位置 $content_start = 0; if (is_array($starting_word)) { $earliest_start = null; $matched_word_len = 0; foreach ($starting_word as $word) { $pos = strpos($str, $word); if ($pos !== false && ($earliest_start === null || $pos < $earliest_start)) { $earliest_start = $pos; $matched_word_len = strlen($word); } } // 没有匹配到任何起始词时返回空字符串 if ($earliest_start === null) return ''; $content_start = $earliest_start + $matched_word_len; } else { $start_pos = strpos($str, $starting_word); if ($start_pos === false) return ''; $content_start = $start_pos + strlen($starting_word); } // 处理终止词匹配:兼容单个字符串/数组形式,取起点之后最早出现的终止位置 if (!is_array($ending_word)) { $ending_word = [$ending_word]; } $earliest_end = null; foreach ($ending_word as $word) { $pos = strpos($str, $word, $content_start); // 跳过未匹配到的终止词,记录所有有效匹配中最靠前的位置 if ($pos !== false && ($earliest_end === null || $pos < $earliest_end)) { $earliest_end = $pos; } } // 所有终止词都没匹配到的场景:返回从起点到文本末尾的内容 if ($earliest_end === null) { return substr($str, $content_start); } // 截取两个位置之间的内容 return substr($str, $content_start, $earliest_end - $content_start); }
效果验证
使用之前的测试样例调用修改后的函数:
$array_a = ['the', 'amen']; $array_b = [',', '.']; $str = "Hello, the world. Then, it is over."; $result = string_between($str, $array_a, $array_b);
返回结果和预期完全一致:the world.
内容的提问来源于stack exchange,提问作者Hymed Ghenai
相关产品推荐
相关产品推荐

