0

我有一个像这样的数组:

arr = array("*" , "$" , "and" , "or" , "!" ,"/");

和另一个字符串,如:

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

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

最简单的方法是使用for循环,但我相信在 PHP 中应该有更有效的方法来做到这一点。

4

3 回答 3

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]);
于 2013-07-05T04:57:49.220 回答
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] => $ )

于 2013-07-05T04:56:21.750 回答
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";
于 2013-07-05T05:09:18.830 回答