Andres SK
Andres SK

Reputation: 10974

Searching strings IN strings with preg

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;
}

Upvotes: 0

Views: 74

Answers (1)

Gordon
Gordon

Reputation: 316969

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

Upvotes: 5

Related Questions