Here is my code:
$txt = 'this is a text';
$word = 'is';
echo str_replace($word, '<b>'.$word.'</b>', $txt);
//=> th<b>is</b> <b>is</b> a text
As you see, my sub-string is is
in example above and it matches just is
part of this
. While I need to select the whole of word. So this is expected result:
//=> <b>this</b> <b>is</b> a text
So I need to check both left and right side of the sub-string and match everything until either first of string ^
or end of string $
or white spage \s
.
How can I do that?
Use a regular expression with word boundary anchors:
$regex = '/\b(\p{L}*' . preg_quote($word, '/') . '\p{L}*)\b/u';
echo preg_replace($regex, '<b>$1</b>', $txt);
where \p{L}
stands for a Unicode letter (see Unicode character classes). If Unicode is not supported, replace \p{L}
with \S
(non-space character), for example.
Output
<b>this</b> <b>is</b> a text
You can use preg_replace
to achieve that with Regex
If you want to match a substring of a word as well as the word itself you can check for any word characters around the word your looking for like so:
$re = '/(\w*is\w*)/';
$str = 'this is a text';
$subst = '<b>$1<b>';
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
This will give you:
<b>this<b> <b>is<b> a text