Trouble Getting Regex Match Correct

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
Superman859
Forum Commoner
Posts: 47
Joined: Sun Oct 29, 2006 10:22 am

Trouble Getting Regex Match Correct

Post by Superman859 »

Hello everyone. I'm having a bit of trouble getting a regex match to work out correctly...Any ideas?

I query a database which is basically a Korean-English and English-Korean dictionary.

Right now I'm trying to get it to return proper results. I use the following for the query:

$query = "SELECT * FROM dictionary WHERE $type LIKE '%$search%'";

$type holds which column to search depending on what user inputs. $search is what they type in for the word.

As it is now, it returns all results that have the $search term anywhere in them. That should be expected based on the wildcard.

However, I want to limit that to anything in the form:

anything (non-word character)$search(non-word character) anything

Basically I don't want to find results when it is in the middle of a word. I only want it to return results if the $search is surrounded by a non-word character (not word boundaries, it can have a space, punctuation, etc. around it).

Here is what I tried first: $row[1] holds the result from the MySQL query..

$pattern = "/.*\W$row[1]\W.*/";

I realize it's greedy and not efficient yet. Regardless, this returns no results.

$pattern = "/.*$row[1].*/"; returns all results.

I've also tried:

$pattern = "/.*[^a-zA-Z]$row[1][^a-zA-Z].*/";

That returns nothing as well.

$pattern = "/$row[1]/"; returns all rows that has the word as well.

It seems like whatever I try doesn't work right. Here is the URL so you can do some test searches...Use the English box, as that is what I am dealing with first.

http://www.learn-korean-now.com/beta/search.php

I keep using the test search 'printer', but have tried with other words as well. I'm trying to eliminate results like 'imprinter' and 'sprinter', but keep results like 'line printer'

Code below:

Code: Select all

$query = "SELECT * FROM dictionary WHERE $type LIKE '%$search%'";

$result = mysql_query($query) or die(mysql_error());

if($result) {
	echo '<table cellpadding="3" cellspacing="3"><tr><th>ID</th><th>English</th><th>Korean</th></tr>';
	
	while($row = mysql_fetch_row($result)) {

		$pattern = "/.*?\W$row[1]\W.*/";
		if( preg_match($pattern, $row[1]) ) {
		echo "<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td></tr>\n";
		}
	}
	
	echo '</table>';
}
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Re: Trouble Getting Regex Match Correct

Post by GeertDD »

Code: Select all

SELECT word
FROM dictionary
WHERE word REGEXP '[[:<:]]printer[[:>:]]'
Post Reply