The Caret Symbol Inside Character Classes in PHP Regex
As you know, the caret inside []
creates
a negation when placed at the beginning of the brackets.
This means it is a special character inside
these brackets. To get the caret as a literal character,
you either need to escape it or move it from
the first position.
Example
In the following example, the search pattern is:
the first character is anything except 'd'
,
followed by two 'x'
letters.
<?php
$str = 'axx bxx ^xx dxx';
$res = preg_replace('#[^d]xx#', '!', $str);
?>
As a result, the following will be stored in the variable:
'! ! ! dxx'
Example
Now the search pattern is: the first character
is 'd'
or '^'
, followed by two
'x'
letters:
<?php
$str = 'axx bxx ^xx dxx';
$res = preg_replace('#[d^]xx#', '!', $str);
?>
As a result, the following will be stored in the variable:
'axx bxx ! !'
Example
You don't have to move the caret from the first position; you can simply escape it with a backslash, and it will represent itself:
<?php
$str = 'axx bxx ^xx dxx';
$res = preg_replace('#[\^d]xx#', '!', $str);
?>
As a result, the following will be stored in the variable:
'axx bxx ! !'
Practice Tasks
Given a string:
<?php
$str = '^xx axx ^zz bkk @ss';
?>
Write a regular expression that will find strings matching the pattern: caret or at symbol, followed by two Latin letters.
Given a string:
<?php
$str = '^xx axx ^zz bkk @ss';
?>
Write a regular expression that will find strings matching the pattern: NOT a caret and NOT an at symbol, followed by two Latin letters.
Given a string:
<?php
$str = '^xx axx ^zz bkk';
?>
Write a regular expression that will find strings matching the pattern: NOT a caret, followed by two Latin letters.