1

我有一个字符串,我想在 PHP 中使用 preg_match 或 preg_match_all 查找单词 A 后跟除单词 B 之外的任何单词的所有出现次数。

例如,假设 A = 'Hello' and B='Bye',我们的字符串是 Str = 'Hello world, Hello Bye, Hello Andy'。然后我们应该能够使用 preg_match 找到“Hello world”和“Hello Andy”。知道我们该怎么做吗?谢谢!

4

3 回答 3

0

或者像这样

<?
$text = 'Hello world, Hello Bye, Hello Andy';
$a = 'Hello';
$b = 'Bye';
$counter = 0;
$words = explode(' ',$text);
foreach($words as $i => $word){
    $word = strtolower(preg_replace('/[^a-z]/i', '', $word));
    if($word==strtolower($a) && isset($words[$i+1]) && strtolower(preg_replace('/[^a-z]/i', '', $words[$i+1]))!=strtolower($b)){
        $counter++;
    }
}
echo $counter;
?>
于 2013-07-13T14:07:49.433 回答
0
$text = 'Hello world, Hello Bye, Hello Andy, Hello';
// initialize counters first
$count_hellos = $count_hello_byes = $count_hello_no_byes = 0;
// look for Hello - Bye
if(preg_match_all('~\\bHello\\b~si', $text, $matches)){
    $count_hellos = count($matches[0]);
    unset($matches);
}
// look for Hello + Bye
if(preg_match_all('~Hello\\W+Bye~si', $text, $matches)){
    $count_hello_byes = count($matches[0]);
    unset($matches);
}
// do the math
$count_hello_no_byes = $count_hellos - $count_hello_byes;
var_dump($count_hello_no_byes); // what you are looking for

^像这样轻松实现

在此处了解更多关于RegEx 速记字符类的信息。

于 2013-07-13T14:00:20.427 回答
0

您可以使用负前瞻

$haystack = 'Hello world, Hello Bye, Hello Andy';
$pattern = '/\bHello\W+(?!Bye)(\w+)/';
preg_match_all($pattern, $haystack, $m);
print_r($m[1]);
/*
Array
(
    [0] => world
    [1] => Andy
)
*/

如果 A 和 B 值是动态的,请确保在将preg_quote()它们插入模式字符串之前使用 转义它们。

于 2013-07-13T14:44:57.097 回答