0

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.

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

5 Comments

no i need to match all the words that are formed by the alphabets n,i,d,h,i that combines and become '/^[nidhi]+$/' regular expression.
nid whats the problem with it? it also formed from [nidhi].
but checkout the database entries. 'nid' is not in the database. this regular expression is being used to filter strings that are formed with 'n','i','d','h'
Your sql query has '%".$s."%'. So when you use nid here it becomes %nid%. That why your nid and nidhi both matches with nidhi in your database.
Try REGEXP '^".$s."$' instead of LIKE '%".$s."%'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.