gpt4 book ai didi

php - 我在这个 php 正则表达式中做错了什么?

转载 作者:行者123 更新时间:2023-12-05 04:23:45 24 4
gpt4 key购买 nike

我有一个问题。我不知道可能是什么原因。我想做的是知道数组的元素是否有某个单词,我使用这个正则表达式 /.*example.*/,这是代码:

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

$matches = [];
$var = "example";

foreach($array as $element)
{
preg_match("/.*$var.*/", $element, $matches);
}

但是当我运行上面的代码并看到 $matches 的值时,它是一个空数组。我做错了什么?

最佳答案

那是因为您正在遍历 $array 并可能在循环后打印结果。

所以 $matches 只包含 $array 中最后一项的匹配元素。但是因为 'no' 是最后一个元素,它不满足正则表达式要求,所以 $matches 是空的。

为了更好地理解正在发生的事情,请在调用 preg_matches() 之后尝试在循环中使用 print_r($matches)

然后,尝试在循环后调用它,看看有什么不同。

关于php - 我在这个 php 正则表达式中做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73656073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com