如何只在字符串中查找完整的单词
<?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";
?>
最佳答案
要查看特定单词是否在字符串中,您可以使用带单词边界的正则表达式,如下所示:
$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
}
这里的\b
表示“一个词的边界”。它实际上不匹配任何字符,只匹配边界,因此它匹配单词和空格之间的边缘,也匹配字符串末端的边缘。
如果需要使其不区分大小写,可以将 i
添加到匹配字符串的末尾,如下所示:"/\b$search\b/i"
.
如果您需要知道结果在字符串中的什么位置,您可以添加第三个 $matches
参数来提供有关匹配的详细信息,如下所示:
if (preg_match("/\b$search\b/", $str, $matches)) {
// word found
$position = $matches[1];
}
关于php - 如何仅在字符串中查找完整的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8898825/