PHP preg_match(): expresii regulate (regex)
โก Rezumat inteligent
Regular Expressions in PHP are pattern-matching tools that validate, split, and replace text in a single expression. This walkthrough covers the core functions preg_match, preg_split, and preg_replace, explains the common metacharacters, and builds a working email validation pattern step by step.

What is Regular expression in PHP?
PHP regular expressions, also known as regex, are a powerful pattern matching tool that can be performed in a single expression. Regular expressions use special characters such as +, -, and ^ to create complex expressions. They can help you accomplish tasks such as validating email addresses, IP addresses, and more.
De ce sฤ folosiศi expresii regulate
- PHP regular expressions simplify identifying patterns in string data by calling a single function. This saves us coding time.
- When validating user input such as email addresses, domain names, telephone numbers, and IP addresses
- Evidenศierea cuvintelor cheie รฎn rezultatele cฤutฤrii
- Cรขnd creaศi un ศablon HTML personalizat. Regex รฎn PHP poate fi folosit pentru a identifica etichetele ศablonului ศi pentru a le รฎnlocui cu date reale.
Funcศii de expresie regulatฤ รฎncorporate รฎn PHP
PHP has built-in functions that allow us to work with regular expressions, which we will learn in this tutorial. Let us look at the commonly used regular expression functions in PHP.
- preg_match() in PHP โ this function is used to perform pattern matching on a string. It returns true if a match is found and false if a match is not found.
- preg_split() in PHP โ this function is used to perform a pattern match on a string and then split the results into a numeric array.
- preg_replace() รฎn PHP โ aceastฤ funcศie este folositฤ pentru a efectua o potrivire de tipar pe un ศir ศi apoi pentru a รฎnlocui potrivirea cu textul specificat.
Below is the syntax for a regular expression function such as preg_match(), preg_split(), or preg_replace().
<?php
function_name('/pattern/',subject);
?>
AICI,
- โfunction_name(โฆ)โ is either preg_match(), preg_split(), or preg_replace().
- โ/โฆ/โ the forward slashes denote the beginning and end of our regular expression
- โโ/pattern/'โ is the pattern that we need to match
- โsubiectโ este ศirul de text cu care trebuie sฤ se potriveascฤ
Let us now look at practical examples that implement the above PHP regex functions.
Preg_match() รฎn PHP
The first example uses the preg_match() function to perform a simple pattern match for the word guru in a given URL.
The code below shows the implementation of the preg_match() function for the above example.
<?php $my_url = "www.guru99.com"; if (preg_match("/guru/", $my_url)) { echo "the url $my_url contains guru"; } else { echo "the url $my_url does not contain guru"; } ?>
Navigaศi la URL http://localhost/phptuts/preg_match_simple.php
Let us examine the part of the code responsible for our output, preg_match(โ/guru/โ, $my_url). HERE,
- โpreg_match(โฆ)โ este funcศia PHP regex
- โ'/guru/'โ este modelul de expresie regulatฤ care trebuie potrivit
- โ$my_urlโ este variabila care conศine textul cu care se potriveศte.
PHP Preg_split()
Let us now look at another example that uses the preg_split() function.
Vom lua o frazฤ ศir ศi o vom exploda รฎntr-o matrice; modelul care trebuie asortat este un singur spaศiu.
ศirul de text care va fi folosit รฎn acest exemplu este โIubesc expresiile obiศnuiteโ.
Codul de mai jos ilustreazฤ implementarea exemplului de mai sus.
<?php $my_text = "I Love Regular Expressions"; $my_array = preg_split("/ /", $my_text); print_r($my_array ); ?>
Navigaศi la URL http://localhost/phptuts/preg_split.php
PHP Preg_replace()
Let us now look at the preg_replace() Funcศia PHP care efectueazฤ o potrivire a modelului ศi apoi รฎnlocuieศte modelul cu altceva.
Codul de mai jos cautฤ cuvรขntul guru รฎn a ลir.
It replaces the word guru with the word guru surrounded by CSS code that highlights the background color.
<?php $text = "We at Guru99 strive to make quality education affordable to the masses. Guru99.com"; $text = preg_replace("/Guru/", '<span style="background:yellow">Guru</span>', $text); echo $text; ?>
Assuming you have saved the file preg_replace.php, browse to the URL http://localhost/phptuts/preg_replace.php
Metacaracterele expresiei regulate
The above examples used very basic patterns. Metacharacters allow us to perform more complex pattern matches, such as testing the validity of an email address. Let us now look at the commonly used metacharacters.
| Metacaracter | Descriere | Exemplu |
|---|---|---|
| . | Se potriveศte cu orice caracter, cu excepศia unei linii noi | /./ se potriveศte cu orice are un singur caracter |
| ^ | Matches the beginning of a string or excludes characters | /^PH/ se potriveศte cu orice ศir care รฎncepe cu PH |
| $ | Matches a pattern at the end of the string | /com$/ matches guru99.com, yahoo.com etc. |
| * | Matches zero or more of the preceding characters | /com*/ se potriveศte cu computerul, comunicarea etc. |
| + | Requires the preceding character(s) appear at least once | /yah+oo/ se potriveศte cu yahoo |
| \ | Used to escape metacharacters | /yahoo+\.com/ trateazฤ punctul ca o valoare literalฤ |
| [...] | Clasa de caractere | /[abc]/ matches a, b or c |
| az | Se potriveศte cu litere mici | /az/ se potriveศte cool, happy etc. |
| AZ | Se potriveศte cu litere mari | /AZ/ se potriveศte cu CE, CUM, DE CE etc. |
| 0-9 | Se potriveศte cu orice numฤr รฎntre 0 ศi 9 | /0-4/ meciuri 0,1,2,3,4 |
Lista de mai sus oferฤ doar metacaracterele cele mai frecvent utilizate รฎn expresiile regulate.
Let us now look at a fairly complex example that checks the validity of an email address.
<?php $my_email = "name@company.com"; if (preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/", $my_email)) { echo "$my_email is a valid email address"; } else { echo "$my_email is NOT a valid email address"; } ?>
Explaining the Email Validation Pattern
AICI,
- โ/โฆ/โ starts and ends the regular expression
- โ^[a-zA-Z0-9._-]โ matches any lower or upper case letters, numbers between 0 and 9, and dots, underscores, or dashes.
- โ+@[a-zA-Z0-9-]โ matches the @ symbol followed by lower or upper case letters, numbers between 0 and 9, or dashes.
- โ+\.[a-zA-Z.]{2,5}$/โ escapes the dot using the backslash, then matches any lower or upper case letters with a character length between 2 and 5 at the end of the string.
Navigaศi la URL http://localhost/phptuts/preg_match.php
As you can see from the above breakdown, metacharacters are very powerful when it comes to matching patterns.




