tags:

views:

35

answers:

1

If someone searches by "ender" and the title of the item is "Henderson", this function should return:

H<span class="mark">ender</span>son

Somehow it is not working when i call mark_match("Henderson","ender");

Any ideas? This is the function that takes the original item title and compares it to the search string:

function mark_match($txt,$s) {
 # Remove unwanted data
 $txt = strip_tags($txt);
 # Remove innecesary spaces
 $txt = preg_replace('/\s+/',' ', $txt);
 # Mark keywords
 $replace = '<span class="mark">\\1</span>';
 foreach($s as $sitem) {
  $pattern = '/('.trim($sitem).')/i';
  $txt = preg_replace($pattern,$replace,$txt); 
 }
 return $txt;
}
+5  A: 

Why the Regex, when you can just use str_replace()?

$term = 'ender';
$span = '<span class="mark">' . $term . '</span>';
$marked = str_replace($term, $span, 'Henderson');
echo $marked; // outputs H<span class="mark">ender</span>son

Regular string functions are usually the faster alternative to Regular Expressions, especially when the string you are looking for is not a pattern, but just a substring.

The Regex version would look like this though:

$term = 'eNdEr';
$span = '<span class="mark">$0</span>';
$marked = preg_replace("/$term/i", $span, 'Henderson');
echo $marked; // outputs H<span class="mark">ender</span>son
Gordon
+1 for pointing out the misuse of RegEx
Adam Kiss
+1 for this should be the approach the OP should go with.
Anthony Forloney
thanks! worked perfectly... but it is better to use str_ireplace to avoid uppercased title issues
andufo
@andufo yes, sorry, I missed the `/i` in the Regex in your question.
Gordon
wait... your solution has a flaw.If the user searches for "EnDeR" the result will be HEnDeRson. How can that issue be avoided?
andufo
@andufo hmm, yes. I've updated with the Regex version then.
Gordon
nice ;) thanks and votes up!
andufo
@andufo: That's the reason why RegEx is not that bad of a choice :)
Romain