欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-05-12 09:24:07
...
$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自动机来做比较快

相关标签: php