[英]How to highlight search keyword using php preg_replace with parentheses?
I want to highlight my keyword search text by using preg_replace in php but the problem is it won't work with parentheses string (
and )
我想通过在php中使用preg_replace突出显示我的关键字搜索文本,但问题是它不适用于括号字符串(
和)
My function look like this... 我的功能看起来像这样......
$text_oritinal = "25 Hours: Colour In White (CD)";
function highlight($text_search, $text_original) {
$str = preg_replace('#'. $text_search .'#i', '<span style="background-color:#FFFF66; color:#FF0000;">\\0</span>', $text_original);
return $str;
}
Full original text is "25 Hours: Colour In White (CD)"
完整的原始文字是"25 Hours: Colour In White (CD)"
For example. 例如。 If I use the keyword 如果我使用关键字
$text_search = "25 Hours: Colour In White";
It return good replaced keyword with highlight background and text color. 它返回带有高亮背景和文本颜色的良好替换关键字。
<span style="background-color:#FFFF66; color:#FF0000;">25 Hours: Colour In White</span> (CD)
but! 但! if I use this keyword included parentheses string (
and )
如果我使用这个关键字包括括号字符串(
和)
$text_search = "25 Hours: Colour In White (CD)";
It NOT return replaced background and text color. 它不会返回替换的背景和文本颜色。
I think it stuck with parentheses string (
and )
我认为它坚持括号字符串(
和)
The question is how to highlight all text keyword matched without any problem with parentheses string (
and )
? 问题是如何突出显示所有匹配的文本关键字而没有括号字符串(
和)
任何问题?
Please share your idea. 请分享你的想法。 Thanks :) 谢谢 :)
You should call preg_quote
: 你应该调用preg_quote
:
function highlight($text_highlight, $text_search) {
$str = preg_replace('#'. preg_quote($text_highlight) .'#i', '<span style="background-color:#FFFF66; color:#FF0000;">\\0</span>', $text_search);
return $str;
}
Explanation: 说明:
Parenthesis are used to create submatches
. 括号用于创建子submatches
。 Using them in your search string, will cause undesired results as they are reserved characters. 在搜索字符串中使用它们会导致意外结果,因为它们是保留字符。 You can prevent this, and other characters by using preg_quote
which escapes regex reserved characters. 你可以通过使用preg_quote
来逃避正则表达式保留字符来阻止这个和其他字符。
Wrap the text you put into the regex in preg_quote 在preg_quote中将您放入正则表达式的文本换行
http://php.net/manual/en/function.preg-quote.php http://php.net/manual/en/function.preg-quote.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.