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 ...";

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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,'"\'')

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.