The question/problem is:
Write a PHP script, which changes the color of the first character of a word.
This challenge tests your knowledge of preg_replace, and regular expressions.
$text = 'PHP Tutorial';
$text = preg_replace('/(\b[a-z])/i','<span style="color: red;">\1',$text);
Let’s break this down.
preg_replace takes the following parameters:
- optional limit
- optional count
The pattern in this case is ‘/(\b[a-z])/i’
Let’s break that down:
It opens with
'/ and ends with
All regular expressions in PHP are going to be enclosed in quotes and a delimiter like the forward slash – like this:
'/ /' – but what’s the
i all about? It simply means “case insensitive”.
Moving inward we have a pair of parenthesis. Parenthesis are used for grouping, but also for something called numbered capturing.
Think of numbered capturing as a way to grab groups of matching patterns and store them for later reference numerically.
Moving further in, we see
\b on the left, followed by
\b means Word Boundary. It will force the pattern that follows to start at the beginning of a word. (Think of it as setting a virtual cursor, or start point, before the word.)
[a-z] matches any one character in that set. (Remember we used
\i to make it case insensitive)
So the pattern will match the first character of a word, but remember that regular expressions are greedy by default, so that means it won’t stop just because it found a match. So it matches the first letter of both words in our example.
If you look further to the right in the regex function you’ll notice that the second parameter contains
\1, which is referring to the first captured item in the capture group. In our case it’s the P and the T – the first letter of each word.
So you can see how it will replace the matched text with the modified code which adds the span tag, but it will only affect one character for each word.
For an easy way to make it only affect the first word, just add a 1 as the 4th parameter to the preg_replace. Recall that is the optional “limit” parameter.