⊗ppPmRgSS 234 of 447 menu

Special Characters Inside Square Brackets in PHP

Special characters inside [] become ordinary characters. This means that they do not need to be escaped with a backslash.

Example

In this example, the search pattern looks like this: between the x's, any letter 'a', 'b', 'c', or a dot:

<?php $str = 'xax xbx xcx xdx x.x x@x'; $res = preg_replace('#x[abc.]x#', '!', $str); ?>

As a result, the following will be stored in the variable:

'! ! ! xdx ! x@x'

Example

In this example, the search pattern looks like this: between the x's, any lowercase Latin letter or a dot:

<?php $str = 'xax xbx xcx x@x'; $res = preg_replace('#x[a-z.]x#', '!', $str); ?>

As a result, the following will be stored in the variable:

'! ! ! x@x'

Practice Tasks

Given a string:

<?php $str = 'aba aea aca aza axa a.a a+a a*a'; ?>

Write a regular expression that will find the strings 'a.a', 'a+a', 'a*a', without affecting the others.

Given a string:

<?php $str = 'xaz x.z x3z x@z x$z xrz'; ?>

Write a regular expression that will find strings matching the pattern: the letter 'x', then NOT a dot, NOT an at sign, and NOT a dollar sign, and then the letter 'z'.

byenru