⊗ppPmRgInr 223 of 447 menu

Introduction to Regular Expressions in PHP

Regular expressions are commands for complex search and replace. They allow doing very interesting things, but, unfortunately, are quite difficult to master.

There are several PHP functions for working with regular expressions. We will start getting acquainted with them using the example of preg_replace. This function takes as the first parameter what to replace, and as the second - what to replace with, and as the third parameter - the string in which to replace:

<?php preg_replace(what to replace, with what, string); ?>

In this case, our function takes as the first parameter not just a string, but a regular expression, which is a string with a set of commands, placed inside the hash characters #. These hashes are called delimiters of regular expressions.

After the delimiters, you can write modifiers - commands that change the general properties of the regular expression.

The regular expressions themselves consist of two types of characters: those that represent themselves and from command characters, which are called special characters.

Letters and numbers represent themselves. In the next example, we will use a regular expression to replace the letter 'a' with '!':

<?php preg_replace('#a#', '!', 'bab'); // returns 'b!b' ?>

But the dot is a special character and represents any character. In the next example, we will find a string by this pattern: letter 'x', then any character, then again the letter 'x':

<?php preg_replace('#x.x#', '!', 'xax eee'); // returns '! eee' ?>

Given a string:

<?php $str = 'ahb acb aeb aeeb adcb axeb'; ?>

Write a regular expression that will find the strings 'ahb', 'acb', 'aeb' by the pattern: letter 'a', any character, letter 'b'.

Given a string:

<?php $str = 'ahb acb aeb aeeb adcb axeb'; ?>

Write a regular expression that will find the strings 'aeeb', 'adcb', 'axeb' by the pattern: letter 'a', two any characters, letter 'b'.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline