Skip to content
Advertisement

Problem with preg-replace: function replaces whole string instead of only part of it

I have one unsolved case. I need to highlight some $search text from $sentence.

$result=preg_replace("/p{L}*?".preg_quote($search)."p{L}*/ui", "<strong style='color:yellow'>$0</strong>", $sentence);

This function does everything good, finds every appearance of substring, but it highlights (replaces) not only the part of word which contains the substr, but the whole word (from whitespase to whitespace).

For example:

$sentence='This is the sentence to be searhed through';
$search = 'sent';
echo $result gives "This is the **sentence** to be searhed through"

But I need

"This is the sentence to be searhed through"

Can somebody help me understanding what i did wrong? Thanks in advance.

Advertisement

Answer

p{L}*? and p{L}*? match zero or more letters (the first one is a lazy variant of the second), thus, you match any word that contains $search.

You can fix it with

$sentence='This is the sentence to be searhed through';
$search = 'sent';
$result = preg_replace("/" . preg_quote($search, "/") . "/ui", "<strong style='color:yellow'>$0</strong>", $sentence);
echo $result;
// => This is the <strong style='color:yellow'>sent</strong>ence to be searhed through

See the PHP demo

Both p{L} containing patterns are removed and the preg_quote also escapes the regex delimiter, see the / second argument to this function.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement