赞
踩
更新:
单词边界无关的解决方案是在输入字符串和搜索词周围添加空格:
$str = ' ' . $str . ' ';
function quote($a) {
return ' ' . preg_quote($a, '/') . ' ';
}
$word_pattern = '/' . implode('|', array_map('quote', $array)) . '/';
if(preg_match($word_pattern, $str) > 0) {
}或通过循环术语:
foreach($array as $term) {
if (strpos($str, ' '. $term . ' ') !== false) {
// word contained
}
}两者都可以用于简化使用的功能,例如,
function contains($needle, $haystack) {
$haystack = ' ' . $haystack . ' ';
foreach($needle as $term) {
if(strpos($haystack, ' ' . $term . ' ') !== false) {
return true;
}
}
return false;
}看一下DEMO
老答案:
你可以使用正则表达式:
function quote($a) {
return preg_quote($a, '/');
}
$word_pattern = implode('|', array_map('quote', $array));
if(preg_match('/\b' . $word_pattern . '\b/', $str) > 0) {
}这里重要的部分是边界字符\b。如果您搜索的值是字符串中的(序列)单词,则只会得到匹配项。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。