SQLiteで正規表現

By ctrans | 2010-11-10

PHP+SQLiteの環境で正規表現を使った検索を行うには、sqlite_create_functionを使ってユーザ定義関数を登録する。

データベースをオープンしたら、sqlite_create_functionにDBのハンドル、登録するユーザ定義関数の名前、そのユーザ定義関数のコールバック関数、ユーザ定義関数の引数の与える。

以下の例ではsqlite_regex_matchというコールバックを用意しているが、見れば分かるようにmb_eregをくるんだだけである。後は例のようにSELECTのWHERE句でRGX(正規表現, 検索対象のカラム)と指定すれば、マッチするデータを返してくれる。手軽だ。

1
2
3
4
5
6
7
8
9
10
11
12
$db = sqlite_open('database');
sqlite_create_function($db, 'RGX', 'sqlite_regex_match', 2);
$query = "SELECT * FROM tabale WHERE RGX('^(mo|ho)ge$', column)";
$result = sqlite_array_query($db, $query, SQLITE_ASSOC);
sqlite_close($db);
 
function sqlite_regex_match($regex, $str) {
    if (mb_ereg($regex, $str)) {
        return 1;
    }
    return 0;
}
web拍手

Leave Your Comment

Your email will not be published or shared.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">