有效检查字符串中的数组项

时间:2013-07-05 04:51:24

标签: php

我有一个像:

这样的数组
arr = array("*" , "$" , "and" , "or" , "!" ,"/");

和另一个字符串如:

string = "this * is very beautiful but $ is more important in life.";

我正在寻找以最低成本找到此字符串中数组成员的最有效方法。此外,我需要在结果中有一个数组,可以显示字符串中存在哪些成员。

最简单的方法是使用for循环,但我相信应该有更有效的方法在PHP中执行此操作。

3 个答案:

答案 0 :(得分:3)

$arr=array("*" , "$" , "#" , "!");

$r = '~[' . preg_quote(implode('', $arr)) . ']~';

$str = "this * is very beautiful but $ is more important in life.";

preg_match_all($r, $str, $matches);

echo 'The following chars were found: ' . implode(', ', $matches[0]);

答案 1 :(得分:0)

您可以使用array_insersect

$string = "this * is very beautiful but $ is more important in life.";
$arr=array("*" , "$" , "#" , "!");

$str = str_split($string);

$out = array_intersect($arr, $str);

print_r($out);

此代码将生成以下输出

  

数组([0] => * [1] => $)

答案 2 :(得分:0)

如果您正在寻找最有效的方法,以下代码的结果是:

预浸料:1.03257489204

array_intersect:2.62625193596

strpos:0.814728021622

看起来像循环数组并使用strpos进行匹配是最有效的方法。

        $arr=array("*" , "$" , "#" , "!");

        $string="this * is very beautiful but $ is more important in life.";



        $time = microtime(true);

        for ($i=0; $i<100000; $i++){

            $r = '~[' . preg_quote(implode('', $arr)) . ']~';

            $str = "this * is very beautiful but $ is more important in life.";

            preg_match_all($r, $str, $matches);

        }

        echo "preg:". (microtime(true)-$time)."\n";

        $time = microtime(true);

        for ($i=0; $i<100000; $i++){

            $str = str_split($string);

            $out = array_intersect($arr, $str);

        }


        echo "array_intersect:". (microtime(true)-$time)."\n";


        $time = microtime(true);

        for ($i=0; $i<100000; $i++){

            $res = array();
            foreach($arr as $a){
                if(strpos($string, $a) !== false){
                    $res[] = $a;
                }
            }

        }

        echo "strpos:". (microtime(true)-$time)."\n";