使用php搜索具有正则表达式条件的数据库

时间:2014-02-27 14:29:37

标签: php mysql regex

我有以下数据库:

database name=words , table name=collection, column name=word
word
----
vivek
nidhi
neha
sidhu
hin

我需要搜索具有正则表达式条件的字符串数组:

<?php
$array=array('vivek','nidhi','neha','akshay','nitin','nid','nih','hin');
@ $db=new mysqli('localhost','root','','words');
if(mysqli_connect_errno())
{
    echo 'Error:Could not connect to the database';
}
else
echo 'connected';
$db->select_db('words');
$count = 0;
foreach($array as $s)
{    
    if(preg_match('/^[nidhi]+$/', $s))
    {
    $query="select * from collection where word LIKE '%".$s."%'";
    $result=$db->query($query);
    if($result)
    $count += $result->num_rows;
    }   

}
echo $count;
$db->close();
?>

我正在使用'/^[nidhi]+$/'正则表达式,所以我应该只获得2 ans i.e. nidhi,hin,但我的问题是我正在考虑3 ans i.e nidhi,nid,hin

1 个答案:

答案 0 :(得分:1)

您目前的做法是匹配由nidhi中的任何字符组成的字词。

如果您只需要匹配nidhihin,那么您应该管道(|)词汇中的字词:

if(preg_match('/^nidhi|hin$/', $s))