Inverting Character Sets in Regex
Using the caret ^ at the beginning of square
brackets allows you to invert the desired set. That is,
if, for example, the pattern [ab] searches for
the letter 'a' or 'b', then the pattern
[^ab] will search for all characters except
'a' and 'b'.
Example
In this example, the search pattern looks like this:
letter 'x', then NOT letter 'a',
not 'b' and not 'c', then letter
'z':
<?php
$str = 'xaz xbz xcz xez';
$res = preg_replace('#x[^abc]z#', '!', $str);
?>
As a result, the following will be written to the variable:
'xaz xbz xcz !'
Example
In this example, the search pattern looks like this:
letter 'x', then NOT a lowercase Latin
letter, then letter 'z':
<?php
$str = 'xaz xbz x1z xCz';
$res = preg_replace('#x[^a-z]z#', '!', $str);
?>
As a result, the following will be written to the variable:
'xaz xbz ! !'
Practice Tasks
Write a regular expression that finds strings
matching the pattern: digit '1', then a character
that is not 'e' and not 'x', digit '2'.
Write a regular expression that finds strings
matching the pattern: letter 'x', then NOT
a digit from 2 to 7, letter 'z'.
Write a regular expression that finds strings
matching the pattern: letter 'x', then NOT
an uppercase Latin letter from 1 or more
times, letter 'z'.
Write a regular expression that finds strings
matching the pattern: letter 'x', then not
an uppercase and not a lowercase Latin letter and not a digit
from 1 to 5 from 1 or more
times, letter 'z'.