The End or Beginning of a Word in PHP Regular Expressions
The \b
command denotes the beginning or end
of a word, and \B
, respectively, denotes
not the beginning and not the end of a word. What is a word?
At first glance, it seems to be something
bounded by spaces, but this is not entirely true.
Look at the following string: 'мама
мыла раму'
. The substring 'мыла'
-
is a word (with spaces on both sides), however,
both 'мама'
and 'раму'
are also words,
which are at the beginning and end of the string.
Let's look at the practical application of this command.
In the following example, the search pattern is as follows:
beginning of a word, lowercase Latin letters
one or more times, end of a word. Thus,
the regex will find all words and replace
them with '!'
:
<?php
echo preg_replace('#\b[a-z]+\b#', '!', 'axx bxx xxx exx'); // will output '! ! ! !'
?>
Given a string:
<?php
$str = 'aaa xaa aaa xbb aaa';
?>
Write a regular expression that will find strings
matching the pattern: letter 'x'
at the beginning
of a word.