0

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

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

4 Comments

thanks! worked perfectly... but it is better to use str_ireplace to avoid uppercased title issues
@andufo yes, sorry, I missed the /i in the Regex in your question.
wait... your solution has a flaw. If the user searches for "EnDeR" the result will be HEnDeRson. How can that issue be avoided?
@andufo: That's the reason why RegEx is not that bad of a choice :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.