Character Groups Inside Square Brackets in PHP
Character groups \d
, \D
, \w
,
\W
, \s
, \S
inside []
will denote exactly groups, that is, they will still
be commands.
Example
In this example, the search pattern looks like this:
between x's any digit, or a letter from
'a'
to 'f'
:
<?php
$str = 'xax xbx x1x x2x xhx x@x';
$res = preg_replace('#x[\da-f]x#', '!', $str);
?>
As a result, the following will be written to the variable:
'! ! ! ! xhx x@x'
Example
In this example, the search pattern looks like this:
letter 'x'
, then not a digit, not a dot,
and not a lowercase Latin letter, then letter
'z'
:
<?php
$str = 'xaz x1z xAz x.z x@z';
$res = preg_replace('#x[^\d.a-z]z#', '!', $str);
?>
As a result, the following will be written to the variable:
'xaz x1z ! x.z !'
Practice Tasks
Write a regex that will find strings
by the pattern: digit or dot from 1
or more times.
Write a regex that will find strings
by the pattern: not a digit and not a letter from 'a'
to 'g'
from 3
to 7
times.