用preg_match找不到文本中短语的贪婪匹配

时间:2013-04-30 05:29:54

标签: php regex

我想在文档中搜索短语(在这种情况下是长尾关键字)但是想在搜索到的单词之间允许空格/单词。

例如,我的文字是:

“ShinyTeeth inc是一家位于田纳西州查塔努加的优秀牙科诊所。”

我正在寻找“牙科诊所查塔努加田纳西州

“CrookedTeeth inc是一个优秀的牙科 诊所,总部设在 Chattanooga 田纳西州。”

我需要一个正则表达式,可以在文本中找到我的关键字,每个关键字之间允许有X空格/单词。在这种情况下,例如,最多两个单词间距,以便它可以识别我在我的文本中找到的关键字。

提前致谢

1 个答案:

答案 0 :(得分:1)

如果您尝试匹配多个短语,则在PHP中使用正则表达式匹配字符串文字会很困难。最好在数据库上使用MySQL全文搜索来执行此类操作。话虽这么说,这里有几个字符串和几个正在测试的正则表达式模式。

<?php

$strings= array('Chattanooga Tennessee dental practice.',
"ShinyTeeth inc is an excellent dental clinic based in Chattanooga, Tennessee.",
"My dentist SmileyTeeth in chattanooga tennessee has the coolest practice.",
"And I'm looking for \"dental clinic chattanooga tennessee\"",
"CrookedTeeth inc is an excellent dental clinic located in Chattanooga, Tennessee.");

$patterns = array(
'!((dental office|dentist|dental practice|dental clinic)[^\s.]?\s+([^\s.]+\s?){0,2}\s+[^\s.]?(Chattanooga(,)?)? (Tennessee)?)!is',
'!((dental|dentist|doctor)\s+(clinic|practice|office)\s+([^\s]+\s?){0,2}\s+(Chattanooga(,)?)? (Tennessee)?)!is',

);
foreach($strings as $string){
    foreach($patterns as $pattern){

        if(preg_match($pattern,$string)){
            echo "\n`$pattern` \"matches\"\n $string\n";
        } else {
            echo "\n`$pattern` \"does not match\"\n $string\n";         
        }
    }

}
?>

<强>输出

  

!((dental office|dentist|dental practice|dental clinic)[^\s.]?\s+([^\s.]+\s?){0,2}\s+[^\s.]?(Chattanooga(,)?)? (Tennessee)?)!is“与查塔努加田纳西州牙科不匹配   实践。

     

!((dental|dentist|doctor)\s+(clinic|practice|office)\s+([^\s]+\s?){0,2}\s+(Chattanooga(,)?)? (Tennessee)?)!is“与查塔努加田纳西州牙科不匹配   实践。

     

!((dental office|dentist|dental practice|dental clinic)[^\s.]?\s+([^\s.]+\s?){0,2}\s+[^\s.]?(Chattanooga(,)?)? (Tennessee)?)!is“匹配”ShinyTeeth inc是一款出色的牙科用品   位于田纳西州查塔努加的诊所。

     

!((dental|dentist|doctor)\s+(clinic|practice|office)\s+([^\s]+\s?){0,2}\s+(Chattanooga(,)?)? (Tennessee)?)!is“匹配”ShinyTeeth inc是一款出色的牙科用品   位于田纳西州查塔努加的诊所。

     

!((dental office|dentist|dental practice|dental clinic)[^\s.]?\s+([^\s.]+\s?){0,2}\s+[^\s.]?(Chattanooga(,)?)? (Tennessee)?)!is“匹配”我的牙医SmileyTeeth在查塔努加   田纳西州有最酷的做法。

     

!((dental|dentist|doctor)\s+(clinic|practice|office)\s+([^\s]+\s?){0,2}\s+(Chattanooga(,)?)? (Tennessee)?)!is“与我的牙医SmileyTeeth不符   查塔努加田纳西州有最酷的做法。

     

!((dental office|dentist|dental practice|dental clinic)[^\s.]?\s+([^\s.]+\s?){0,2}\s+[^\s.]?(Chattanooga(,)?)? (Tennessee)?)!is“不匹配”我正在寻找“牙科诊所   查塔努加田纳西州“

     

!((dental|dentist|doctor)\s+(clinic|practice|office)\s+([^\s]+\s?){0,2}\s+(Chattanooga(,)?)? (Tennessee)?)!is“不匹配”我正在寻找“牙科诊所   查塔努加田纳西州“

     

!((dental office|dentist|dental practice|dental clinic)[^\s.]?\s+([^\s.]+\s?){0,2}\s+[^\s.]?(Chattanooga(,)?)? (Tennessee)?)!is“匹配”CrookedTeeth inc是一个很好的牙科   诊所位于田纳西州查塔努加。

     

!((dental|dentist|doctor)\s+(clinic|practice|office)\s+([^\s]+\s?){0,2}\s+(Chattanooga(,)?)? (Tennessee)?)!is“匹配”CrookedTeeth inc是一个很好的牙科   诊所位于田纳西州查塔努加。