regex字符串替换上和小写。

时间:2021-11-06 13:05:46

Given the following simple function (for a PHP page) I am trying to match all the occurences of the word $marker in a long text string. I need to highlight its occurences. The function works, but it presents two problems:

给定以下简单的函数(对于PHP页面),我将尝试在一个长文本字符串中匹配所有出现的$marker。我需要强调它的发生。这个函数可以工作,但它存在两个问题:

1) it fails to match uppercase occurences of $marker

1)无法匹配$marker的大写字母出现

2) it also matches partial occurences: if $marker is "art", the function as it is also matches "artistic" and "cart".

2)也匹配部分出现:如果$marker是“art”,其功能也匹配“art”和“cart”。

How can I correct these two inconveniences?

我怎样才能纠正这两种不便呢?

function highlightWords($string, $marker){
$string = str_replace($marker, "<span class='highlight success'>".$marker."</span>", $string);
return $string;
}

1 个解决方案

#1


3  

To solve the two problems you can use preg_replace() with a regular expression. Just add the i flag for case-insensitive search and add \b word boundaries around your search term, so it can't be part of another word, e.g.

要解决这两个问题,可以使用preg_replace()和正则表达式。只需要为不区分大小写的搜索添加i标志,并在你的搜索词周围添加b字边界,这样它就不会是另一个词的一部分,例如。

function highlightWords($string, $marker){
    $string = preg_replace("/(\b" . preg_quote($marker, "/") . "\b)/i", "<span class='highlight success'>$1</span>", $string);
    return $string;
}

#1


3  

To solve the two problems you can use preg_replace() with a regular expression. Just add the i flag for case-insensitive search and add \b word boundaries around your search term, so it can't be part of another word, e.g.

要解决这两个问题,可以使用preg_replace()和正则表达式。只需要为不区分大小写的搜索添加i标志,并在你的搜索词周围添加b字边界,这样它就不会是另一个词的一部分,例如。

function highlightWords($string, $marker){
    $string = preg_replace("/(\b" . preg_quote($marker, "/") . "\b)/i", "<span class='highlight success'>$1</span>", $string);
    return $string;
}