PHPで標準あいまい検索
7月 11th, 2007 admin Posted in PHP | 3 Comments »
あいまい検索の実装について考えていたら、考えるまでもなく標準で実装されていました。similar_textっていう関数らしいです。
php.netのあいまい検索を使ってJavaScriptのリファレンスを検索する
http://labs.gmo.jp/blog/ku/2007/04/phpnetjavascript.html
PHPには similar_text という二つの文字列が似ている度合いを計算してくれる関数があるのをこのとき知りました。それもPHP4からあります。PHPは文字列の類似性判定をする関数が豊富で、このほかにも levenshtein, soundex, metaphone があるそうです。
すごいなー。英単語にいたっては音が類似しているものまで検索可能だそうです・・・こういうのが標準で入ってるあたりがPHPっぽいですね。
早速試してみました。日本語でもなんとなくいけているっぽいです。
コード
noreturn.php
<form action="" method="get">
<input type="text" name="str" value="<?=$_GET['str']?/>">
<input type="submit" name="submit" value="あいまい検索"/>
</form>
< ?php
$dic = array("ノーダウト","ノープロブレム","ノーリスク","ノーリターン");
$point = 0;
$per = 0;
$answer = '';
if(isset($_GET['str'])){
$str = $_GET['str'];
foreach($dic as $word){
$new_point = similar_text($word,$str,$per);
echo $word."と".intval($per)."%似ています<br>";
if($point < $new_point){
$point = $new_point;
$answer = $word;
}
}
echo "<br>もしかして<strong>".$answer."</strong>?";
}
?>
11月 30th, 2009 at 13:50:32
面白いサンプルを教えていただき、ありがとうございます。
二行目のshorttagが ”?/>”” でなく ”?>” /”かもですね。
11月 18th, 2010 at 17:35:20
おお
phpにそんな関数があったとは!しかも標準で。。
12月 4th, 2010 at 18:55:05
xenical y embarazo, xenical costo, xenical generico xenical dosificacion, xenical se vende con receta en chile