preg_grep函数找不到任何东西(php)

时间:2015-05-21 12:40:47

标签: php regex

我讨厌提出这样的问题,因为答案是'我很愚蠢'或'我的电脑有奇怪的问题'......(而且第一个问题可能是正确的问题)但是我被困在了那个:

$matches = preg_grep("(.+)","ThisIsATest");
error_log(count($matches), 3, "php.log");

日志给我0,无论我作为模式给出什么......我无法理解为什么这个$matches变量总是空的!

3 个答案:

答案 0 :(得分:2)

preg_grep不是用于搜索字符串,而是用于搜索字符串数组......您应该使用preg_match代替。

答案 1 :(得分:1)

这是你应该得到的错误:

preg_grep() expects parameter 2 to be array, string given

这是一种使用preg_match返回一个匹配(在这种情况下,您只有1个)的方法:

preg_match("(.+)","ThisIsATest", $matches);
print_r($matches);

请参阅IDEONE demo

要使用$matches[0]访问该值,您需要使用preg_match_all

preg_match_all("(.+)","ThisIsATest", $matches);
print_r($matches[0]);

请参阅another demo

答案 2 :(得分:0)

您似乎只是使用了错误的方法:

if (preg_match('/(.+)/', "ThisIsATest")) {
   # Successful match
} else {
   # Match attempt failed
}