7

PHP 検索関数を作成したいのですが、Google のような演算子を使用しています。例えば:

these words "this phrase" location:"Los Angeles" operator:something

location: のような演算子は、スペースを含む値をサポートすることが重要です (したがって、この例では引用符を使用しています)。そのため、単純に分割したり、標準のトークンを使用したりすることはできません。ある時点で誰かがこれを行うためのライブラリを作成したと思いますが、見つかりません。

または、ライブラリが必要ない場合は、これを行う良い方法が良いでしょう。

必要なのは検索クエリの解析だけです。つまり、上記のクエリから、次のもので構成される配列を取得しても問題ありません。

[0] => these
[1] => words
[2] => "this phrase"
[3] => location:"Los Angeles"
[4] => operator:something

そこから、データベースの検索機能を構築できます。

4

1 に答える 1

14

str_getcsv()から始めて区切り文字としてスペースを使用できますが、その特定のケースで引用符を処理するために場所と演算子を前処理する必要がある場合があります。

<?php
$str = 'these words "this phrase" location:"Los Angeles" operator:something';

// preprocess the cases where you have colon separated definitions with quotes
// i.e. location:"los angeles"
$str = preg_replace('/(\w+)\:"(\w+)/', '"${1}:${2}', $str);

$str = str_getcsv($str, ' ');

var_dump($str);
?>

出力

array(5) {
  [0]=>
  string(5) "these"
  [1]=>
  string(5) "words"
  [2]=>
  string(11) "this phrase"
  [3]=>
  string(20) "location:Los Angeles"
  [4]=>
  string(18) "operator:something"
}
于 2013-03-03T22:02:19.170 に答える