Vivek
Vivek

Reputation: 373

searching database with regular expression condition using php

I have database as following:

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

I need to search an array of strings with regular expression condition:

<?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();
?>

i am using '/^[nidhi]+$/' regular expression so I should get only 2 ans i.e. nidhi,hin but my problem is I am geting 3 ans i.e nidhi,nid,hin.

Upvotes: 0

Views: 139

Answers (1)

Sabuj Hassan
Sabuj Hassan

Reputation: 39365

The way you are currently doing is matching the words, which are formed from any of the characters in nidhi.

If you need to match only nidhi and hin then you should pipe (|) the words in the exression:

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

Upvotes: 1

Related Questions