PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

php 判断字符串是否包含数组中的某个元素

原创
2016-06-06 20:22:09 1929浏览

$str="woxiangyao_genghao-de-zifuchuan";
$arr = array('geng','de','cdaefad');
foreach($arr as $v){

if(strpos($str, $v) !== false){
    echo $str;
    exit;
}

}
有没有效率更高的写法?

回复内容:

$str="woxiangyao_genghao-de-zifuchuan";
$arr = array('geng','de','cdaefad');
foreach($arr as $v){

if(strpos($str, $v) !== false){
    echo $str;
    exit;
}

}
有没有效率更高的写法?

我将问题理解成如何判断内容是否包含敏感词,题主可将敏感词生成成字典树,然后再查找内容是否包含关键词
下面是一个简单的PHP字典树的示例,供参考

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 

如果不考虑语言角度,应该用AC自动机来做比较快

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。