preg_match_all返回模式匹配而不是主题匹配

时间:2016-08-10 16:09:15

标签: php regex

我试图从字符串返回匹配项,如下所示:

$subject = "The quick brown fox jumps over the lazy dog";
$pattern = "/(Dog|Brown|Fox)/i";
$pregMatchCount = preg_match_all($pattern, $subject, $matches);
print_r($matches);

但是,由于不区分大小写的修饰符,这会返回一个如下所示的数组:

Array
    (
        [0] => dog
        [1] => brown
        [2] => fox
    )

不区分大小写的修饰符很重要,因为模式将动态生成。还有其他方法可以解决这个问题,但如果在这种情况下有一种方法可以捕获模式匹配,那么它会更好(也更有效),如下所示:

Array
    (
        [0] => Dog
        [1] => Brown
        [2] => Fox
    )

提前致谢。

2 个答案:

答案 0 :(得分:2)

我强烈建议不要使用正则表达式来完成此任务,因为它不需要。只需使用stripos()来确定某个项目是否在字符串中。

function findMatches($subject, $items)
{
    $matches = array();
    foreach ( $items as $item )
    {
        if ( stripos($subject, $item) !== false )
        {
            $matches[] = $item;
        }
    }

    return $matches;
}

$subject = "The quick brown fox jumps over the lazy dog";

print_r(findMatches($subject, array('Dog', 'Brown', 'Fx')));

请参阅this fiddle了解演示/效果统计信息。

你也可以做一个简单的array_filter:

$subject = "The quick brown fox jumps over the lazy dog";


print_r(array_filter(array('Dog', 'Brown', 'Fx'), function($item) use ($subject) {
     return stripos($subject, $item) !== false;
}));

答案 1 :(得分:0)

我相信最初的答案,虽然它解决了OP 所述的样本问题,但并没有解决标题中提出的主要问题。

想象一下,有人拼命寻找这个/某些问题的答案,在Stack Overflow上找到这个页面......并且答案不能解决标题中陈述的原始问题但是会是& #34;替代解决方案"可能是孤立的,从而减少了问题。

总之...

我就是这样做的。

<?php

$subject = "The quick brown fox jumps over the lazy dog";

$needles = [
    'Dog',
    'Clown',
    'Brown',
    'Fox',
    'Dude',
];

// Optional: If you want to search for the needles as they are,
// literally, let's escape possible control characters.
$needles = array_map('preg_quote', $needles);

// Build our regular expression with matching groups which we can then evaluate.
$pattern = sprintf("#(%s)#i", implode(')|(', $needles));

// In this case the result regexp. would be:
// #(Dog)|(Clown)|(Brown)|(Fox)|(Dude)#i

// So let's match it!
$pregMatchCount = preg_match_all($pattern, $subject, $m);

// Get rid of the first item as it represents all matches.
array_shift($m);

// Go through each of the matched sub-groups...
foreach ($m as $i => $group) {

    // ...and if this sub-group is not empty, we know that the needle
    // with the index of this sub-group is present in the results.
    if (array_filter($group)) {
        $foundNeedles[] = $needles[$i];
    }

}

print_r($foundNeedles);

结果是:

Array
(
    [0] => Dog
    [1] => Brown
    [2] => Fox
)