代码之家  ›  专栏  ›  技术社区  ›  Young

检测由另一个不连续字符串包含的字符串

  •  0
  • Young  · 技术社区  · 16 年前

    最近我正在处理bbs的坏内容(如advertise post)过滤器。我编写了一个函数来检测一个字符串是否在另一个字符串中,而不是连续的。代码如下:

    $str = 'helloguys';
    $substr1 = 'hlu';
    $substr2 = 'elf';
    
    function detect($a,$b) //function that detect a in b
    {
        $c = '';
        for($i=0;$i<=strlen($a);$i++)
        {
            for($j=0;$j<=strlen($b);$j++)
            {
                if($a[$i] == $b[$j])
                {
                   $b=substr($b,$j+1);
                   $c .=$a[$i];
                   break;
                }
            }
        }
        if($c == $a) return true;
        else return false;
    }
    
    var_dump(detect($substr1,$str)); //true
    var_dump(detect($substr2,$str)); //false
    

    因为过滤器在用户发帖之前就工作了,所以我认为这里的效率很重要。我想知道是否有更好的解决方案?谢谢!

    2 回复  |  直到 16 年前
        1
  •  1
  •   Du Song    16 年前

    一种更快的方法是将$A转换为正则表达式并将其与$B匹配,这样您只需将优化留给用C代码编写的PCRE模块本身。

    例如:

    detect("hlu",$b) is equal to preg_match("/h.*l.*u/", $b)
    (detect("hlu",$b) && detect("elf",$b)) is equal to preg_match("/(h.*l.*u|e.*l.*f)/", $b)
    
        2
  •  0
  •   Galen    16 年前

    不知道你为什么要这样做。但我很无聊

    function detect( $a,$b ) {
    
        return count( array_intersect( str_split($b), str_split($a) ) ) == strlen($b);
    
    }
    
    推荐文章