如何只在字符串中查找完整单词

San*_*han 5 php

如何只在字符串中查找完整单词

<?php
$str ="By ILI LIKUALAYANA MOKHTAKUALAR AND G. SURACH Datuk Dr Hasan Ali says he has no intention of joining Umno. Pic by Afendi Mohamed KUALA LUMPUR: FORMER Selangor Pas commissioner Datuk Dr Hasan Ali has not ruled out the possibility of returning to Pas' fold";
$search ="KUALA";
?>
Run Code Online (Sandbox Code Playgroud)

Ben*_*Lee 14

要查看特定单词是否在字符串中,您可以使用带有单词边界的正则表达式,如下所示:

$str = "By ILI LIKUALAYANA MOKHTAKUALAR AND G. SURACH Datuk Dr Hasan Ali says he has no intention of joining Umno. Pic by Afendi Mohamed KUALA LUMPUR: FORMER Selangor Pas commissioner Datuk Dr Hasan Ali has not ruled out the possibility of returning to Pas' fold";
$search = "KUALA";

if (preg_match("/\b$search\b/", $str)) {
    // word found
}
Run Code Online (Sandbox Code Playgroud)

\b意味着"一个词的边界".它实际上不匹配任何字符,只是边界,因此它匹配单词和空格之间的边,并且还匹配字符串末尾的边.

如果你需要使它不区分大小写,你可以添加i到匹配字符串的末尾,如下所示:"/\b$search\b/i".

如果您需要知道结果在字符串中的哪个位置,您可以添加第三个$matches参数,该参数提供有关匹配的详细信息,如下所示:

if (preg_match("/\b$search\b/", $str, $matches)) {
    // word found
    $position = $matches[1];
}
Run Code Online (Sandbox Code Playgroud)

  • 我没有-1 Wouter的答案,但是如果你要使用正则表达式,这是更好的表达式(因为它'理解'新行,字符串开头没有空格等) (2认同)

Ben*_*n D 5

只需拆分字符串:

$words = explode(' ',$str);
if (in_array($search,$words)){
    echo "FOUND!";
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要该位置:

$words = explode(' ',$str);
$exists_at = array_search($seach,$words);
if ($exists_at){
   echo "Found at ".$exists_at." key in the \$word array";
}
Run Code Online (Sandbox Code Playgroud)

EDITS:

鉴于正在进行的正规革命正反革命斗争正在进行中,我必须撤回这个答案并推迟到正则表达式人群,但我将把它留下来作为历史记录.我一直认为从处理的角度来看,使用数组效率更高,但我决定进行一些测试,结果证明我的假设是错误的.单字测试的结果:

Time to search for word 10000 times using in_array(): 0.011814

Time to search for word 10000 times using preg_match(): 0.001697
Run Code Online (Sandbox Code Playgroud)

我用来测试的代码(假设每次都会使用爆炸):

$str ="By ILI LIKUALAYANA MOKHTAKUALAR AND G. SURACH Datuk Dr Hasan Ali says he has no intention of joining Umno. Pic by Afendi Mohamed KUALA LUMPUR: FORMER Selangor Pas commissioner Datuk Dr Hasan Ali has not ruled out the possibility of returning to Pas' fold";
$search ="KUALA";

$start = microtime(true);
for($i=0;$i<1000;$i++){
    $words = explode(' ',$str);
    if (in_array($search,$words)){
        //
    }

}

$end = microtime();

$total = $end-$start;
echo "Time to search for word 10000 times using in_array(): ";
echo $total;

echo "<br />";

$start = microtime(true);
for($i=0;$i<1000;$i++){
    if (preg_match("/\b$search\b/", $str)) {
        // word found
    }
}

$end = microtime();

$total = $end-$start;
echo "Time to search for word 10000 times using preg_match(): ";
echo $total;
Run Code Online (Sandbox Code Playgroud)

所以结论:使用preg_match("/\b $ search\b /",$ str)