当前位置:   article > 正文

php数组中是否包含某字符串中,PHP如何测试数组中某个值是否存在(部分)在字符串中?...

php if判断某个值是否在字符串中存在

更新:

单词边界无关的解决方案是在输入字符串和搜索词周围添加空格:

$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。如果您搜索的值是字符串中的(序列)单词,则只会得到匹配项。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/634229
推荐阅读
相关标签
  

闽ICP备14008679号