⊗ppPmRgOC 241 of 447 menu

The 'or' Command in PHP Regular Expressions

In this lesson, we will break down the command |, which is a more powerful version of OR compared to the command []. This command allows you to split the regex into several parts. The search term can match either one part of the regex or another. Let's look at some examples.

Example

In this example, the search pattern is: three letters 'a' or three letters 'b':

<?php $str = 'aaa bbb abb'; $res = preg_replace('#a{3}|b{3}#', '!', $str); ?>

As a result, the following will be written to the variable:

'! ! abb'

Example

In this example, the search pattern is: three letters 'a' or from 1 and more letters 'b':

<?php $str = 'aaa bbb bbbb bbbbb axx'; $res = preg_replace('#a{3}|b+#', '!', $str); ?>

As a result, the following will be written to the variable:

'! ! ! ! axx'

Example

In this example, the search pattern is: one or more letters or three digits:

<?php $str = 'a ab abc 1 12 123'; $res = preg_replace('#[a-z]+|\d{3}#', '!', $str); ?>

As a result, the following will be written to the variable:

'! ! ! 1 12 !'

Example

The vertical bar can divide the regex into not two parts, but any number of parts:

<?php $str = 'aaa bbb ccc ddd'; $res = preg_replace('#a+|b+|c+#', '!', $str); ?>

As a result, the following will be written to the variable:

'! ! ! ddd'

Example

If the vertical bar is inside round brackets, then 'or' works only inside these brackets. For example, let's find strings by the following pattern: at the beginning is either 'a', or 'b' one or more times, and then two letters 'x':

<?php $str = 'axx bxx bbxx exx'; $res = preg_replace('#(a|b+)xx#', '!', $str); ?>

As a result, the following will be written to the variable:

'! ! ! exx'

Practice Tasks

Given a string:

<?php $str = 'aeeea aeea aea axa axxa axxxa'; ?>

Write a regex that will find strings by the pattern: the edges are letters 'a', and between them - either the letter 'e' any number of times or the letter 'x' any number of times.

Given a string:

<?php $str = 'aeeea aeea aea axa axxa axxxa'; ?>

Write a regex that will find strings by the pattern: the edges are letters 'a', and between them - either the letter 'e' two times or the letter 'x' any number of times.

byenru