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

PHP正则表达式匹配数组元素结果为空,求排查错误原因

问题分析与解决

你的代码存在两个核心问题:

  1. $matches被循环重复重置
    每次调用preg_match时,都会清空并重新赋值$matches数组。你的循环最后处理的是数组元素'no',这个元素完全不匹配正则表达式,所以最终$matches会被置为空数组。

  2. 正则表达式冗余
    你使用的/.*example.*/完全没必要加首尾的.*——preg_match默认不需要匹配整个字符串,只要目标字符串中包含匹配片段就会返回成功。直接用/$var/就足够判断元素是否包含指定单词。

修正后的代码示例

如果需要收集所有包含指定单词的数组元素,可以这样写:

$array = ['example1', '2example', 'no'];
$var = "example";
$matches = [];

foreach($array as $element) {
    // 匹配成功就将元素加入结果数组
    if(preg_match("/$var/", $element)) {
        $matches[] = $element;
    }
}

print_r($matches); // 输出: Array ( [0] => example1 [1] => 2example )

如果只是需要判断数组中是否存在包含指定单词的元素,用strpos会更高效(无需启动正则引擎):

$array = ['example1', '2example', 'no'];
$var = "example";
$hasMatch = false;

foreach($array as $element) {
    if(strpos($element, $var) !== false) {
        $hasMatch = true;
        break; // 找到匹配项后直接终止循环
    }
}

var_dump($hasMatch); // 输出: bool(true)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:48:26