Home > Article > Backend Development > php 判断字符串是否包含数组中的某个元素
$str="woxiangyao_genghao-de-zifuchuan";
$arr = array('geng','de','cdaefad');
foreach($arr as $v){
<code>if(strpos($str, $v) !== false){ echo $str; exit; }</code>
}
有没有效率更高的写法?
$str="woxiangyao_genghao-de-zifuchuan";
$arr = array('geng','de','cdaefad');
foreach($arr as $v){
<code>if(strpos($str, $v) !== false){ echo $str; exit; }</code>
}
有没有效率更高的写法?
我将问题理解成如何判断内容是否包含敏感词,题主可将敏感词生成成字典树
,然后再查找内容是否包含关键词
下面是一个简单的PHP字典树
的示例,供参考
<code>class TrieTree { public $tree = array(); /** * 增加关键词到字典树 * * @param string $utf8_str */ public function add($utf8_str) { $chars = &UTF8Util::getChars($utf8_str); // 串结尾字符 $chars[] = null; $count = count($chars); $T = &$this->tree; for ($i = 0; $i _find($chars)) { $chars[] = null; $count = count($chars); $T = &$this->tree; for ($i = 0; $i _find($chars); } private function _find(&$chars) { $count = count($chars); $T = &$this->tree; for ($i = 0; $i tree; $count = 0; for ($i = 0; $i contain($str)) { return true; } } } return false; } /** * 导出序列化后的字典树 * * @return string */ public function export() { return serialize($this->tree); } /** * 导入序列化后的字典树 * * @param string $str */ public function import($str) { $this->tree = unserialize($str); } } class UTF8Util { public static function getChars($utf8_str) { $s = $utf8_str; $len = strlen($s); if ($len == 0) return array(); $chars = array(); for ($i = 0; $i > 7) == 0) { $chars[] = $c; } else // 1111 xxxx, first in four char if (($n >> 4) == 15) { if ($i > 5) == 7) { if ($i > 6) == 3) { if ($i </code>
如果不考虑语言角度,应该用AC自动机来做比较快