2012年6月4日月曜日

phpで文字列が含まれているかを調べる

phpで日本語を含む特定の文字列が含まれているかを調べる場合、mb_strpos/mb_striposとpreg_matchが思い浮かびますが、どっちを使うほうがいいのか速度を測ってみました。
<?php
    $title = 'イッタラ(iittala)/カステへルミ(Kastehelmi) ボウル(サンド)';
    $keywords = array('イッタラ', 'カステヘルミ', 'サンド');

    echo "mb_stripos()\n";
    $stime = microtime(true);
    for ($i = 0; $i < 10000; $i++) {
        foreach ($keywords as $word) {
            mb_stripos($title, $word);
        }
    }
    $etime = microtime(true);
    echo 'finish:' . ($etime - $stime) . "\n";

    echo "preg_match()\n";
    $stime = microtime(true);
    for ($i = 0; $i < 10000; $i++) {
        foreach ($keywords as $word) {
            preg_match('/$word/iu', $title);
        }
    }
    $etime = microtime(true);
    echo 'finish:' . ($etime - $stime) . "\n";
?>
結果は以下の通りで、preg_match()の圧勝です。
$ php -f stripos.php 
mb_stripos()
finish:1.6117179393768
preg_match()
finish:0.041254997253418
$ php -f stripos.php 
mb_stripos()
finish:1.6633319854736
preg_match()
finish:0.047746181488037
$ php -f stripos.php 
mb_stripos()
finish:1.615149974823
preg_match()
finish:0.040589094161987

0 件のコメント:

コメントを投稿