1

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.

1 Answer 1

1

\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.

Sign up to request clarification or add additional context in comments.

Comments

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.