LoginSignup
1
1

More than 5 years have passed since last update.

PHPで3単語以上の文字列検索した時のメモ

Last updated at Posted at 2018-10-19

なにしたの

PHPでTwitterのツイートを取得して特定ハッシュタグのツイートだけ取得したいと思った時
preg_matchで検索するべきかstrposでするべきか迷ったから処理速度調べてみた。

動的に正規表現を作ったケースでないため固定の文言でのみの結果となります
動的な場合も追って追加します

結果

こんにちは、これは#テストケースです。これから#時間を#報告します。
から#テストケース、#時間、#時間の順で100万回文字列検索をかけた結果

method time
strpos 24.532892942429
preg_match 25.085613012314

こんにちは、これは#テストケースです。これから#時間を#報告します。
こんにちは、これは#テストケースです。これから#時間を#申請します。
を交互に文字列検索をかけて50万件ヒットさせた結果

method time
strpos 12.542304039001
preg_match 12.694728136063

テストコード

check.php
<?php

    $text1 = 'こんにちは、これは#テストケースです。これから#時間を#報告します。';
    $text2 = 'こんにちは、これは#テストケースです。これから#時間を#申請します。';
    $flg = true;

    $start_time = microtime(true);
    for ($i =0; $i < 1000000; $i++) {
        if ($flg) {
            $text = $text1;
        } else {
            $text = $text2;
        }
        $flg = !$flg;

        if (strpos($text, '#テストケース') !== false) {
            if (strpos($text, '#報告') !== false) {
                if (strpos($text, '#時間') !== false) {
                    echo($i.'回目'.PHP_EOL);
                }
            }
        }
    }
    $end_time = microtime(true) - $start_time;
    // 24.532892942429
    // 12.542304039001

    $reg = '/^(?=.*#テストケース)(?=.*#報告)(?=.*#時間).*$/';
    $start_time = microtime(true);
    for ($i =0; $i < 1000000; $i++) {
        if ($flg) {
            $text = $text1;
        } else {
            $text = $text2;
        }
        $flg = !$flg;
        if (preg_match($reg, $text)) {
            echo($i.'回目'.PHP_EOL);
        }
    }
    $end_time = microtime(true) - $start_time;
    //25.085613012314
    //12.694728136063

    echo($end_time);

まとめ

正規表現よりstrposのが単純なものは早いのかもしれないけれど
複数の文字列検索する場合はそこまで大きな差が見られなかった。

膨大なループで検索する場合を除いてそこまで神経質になる必要もないのかもしれない。

テストケースが間違ってたりすることもあるので
その際はコメントなり編集リクエストで教えてもらえると助かります。

同じように迷った人がいれば。

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1