Jump to content

keyword search picks up every letter, not words


tryingtolearn

Recommended Posts

Not sure if this is the correct spot for this question.

 

I am trying a keyword search example I found on the forum (Cant remember where though)

 

It works great except that it picks up on single letters.

 

If I type g I would get green go tough

where I would want 0 returned

 

Here is the code - is there something in there that would limit it to complete words instead of single letter or letter combo matches

(I was reading about the \b - word boundries but thats in there so I dont think that does what Im thinking it means by the name, bound it to words!!)

 

$query = "SELECT ... AND ";

// clean up your search first
$search = trim($_POST['keyword']);
$search = strip_tags($search);
$search = mysql_real_escape_string($search);

preg_match_all('|(")([^"]+)\\1|', $search, $groups, PREG_PATTERN_ORDER);
preg_match_all('|\b([a-z\d_-]+)\b|i', $search, $words, PREG_PATTERN_ORDER);

$like = array();
if (count($groups) > 0) {
  foreach ($groups[2] as $x) {
    $like[] = "keywords LIKE \"%$x%\"";
  }
}

if (count($words) > 0) {
  foreach ($words[1] as $x) {
    $like[] = "keywords LIKE \"%$x%\"";
  }
}

$query .= "((" . implode(") OR (", $like) . ")) "."AND ...";

I woke up this morning and noticed how sleepy I was last night based on my previous post. (People who know regular expressions like me would agree that I was out of it... or they just think I don't know my stuff.)

 

Anyway... I made you a much better example:

$search = '"php help" freaks"'; // Example search
$like = array();
if (preg_match_all("#\"[^\"]+\"|\w+#i",$search,$matches)){
foreach($matches[0] AS $val){
  $like[] = 'keywords LIKE "%'.trim($val,'"').'%"';
}
}
var_dump($like); // Look good?

After a little more thinking... I think you should use this regular expression:

preg_match_all("#(\"|')[^\\1]+\\1|[^\"'\s]+#i",$search,$matches)

It will match anything with both double and single quotes and anything that doesn't have a quote or space.

 

Also add a single quote to the trim():

trim($val,'"\'')

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.