开发者

Searching strings IN strings with preg

开发者 https://www.devze.com 2022-12-20 06:40 出处:网络
If someone searches by \"ender\" and the title of the item is \"Henderson\", this function should return:

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,$r开发者_如何学运维eplace,$txt); 
 }
 return $txt;
}


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号