PHP

PHP Regular Expressions

In this tutorial, we are going to have an understanding of the PHP Regular Expressions cheat sheet, let’s begin the tutorial with an introduction first.

Introduction

A PHP Regular Expression or Regex (Regexes), is a technique that is used to match or search an expression from a specified string. By matching an expression we mean if you want to search a word, symbol, character, file, etc from a particular string so you can take favor from the regular expressions, basically the regular expression is a unique way to describe an expression or string pattern with some different symbols understandable by computer systems, these expressions are used by most of the programming languages or we can say it a programming language itself that performs string pattern matching tasks.

Regular Expressions aim to reduce code complexity and matched the required expression for the user. Regular expressions are the logic behind text or code editors like notepad, sublime, and visual studio code because it shows suggestions and lets the user match an expression from the written document and code.

The regular expressions are the combination of arithmetic operators that can perform the validation tasks as well like, as validating account IDs, contact information, IP address, etc.

The PHP regular expression is a complex topic we will try to cover all its basic concepts. First, let’s see how to write a regular expression or string pattern.

The regular expression syntax involves some arithmetic operators and different symbols, these operators and symbols are explained below:

(“/string/”)

The above expression is a basic string pattern, we used the inverted commas and between two back slashes, we specified our string. 

(“/string/”)

If you want the results in both uppercase and lowercase use “i” with the expression above.

(“/string|string|string/”)

The above expression will allow you to match multiple strings by using the (pi) “|” symbol after each string.

You can search for numbers and letters as well.

(“[stringstring]”)

The character sets can be used as an alternative to the pi(|) symbol. If you want to match multiple strings or characters just use the expression above.  You don’t need to add any symbol as a separator in the above expression.

(“[a-z]”)

The above expression will be used to specify the range, which means you match characters from a to z in lowercase.

(“[A-Z]”)

The above expression will match the characters from A to Z in Uppercase.

(“[a-z]+”)

The above expression can be used when you want to match more than one lowercase letter. 

(“[^a-z]”)

The above expression can be used when you want to match all letters except the lower one.

(“[A-Zd-k1-10]{1,}$”)

The above expression will match the expression from the specified strings and will return a string with a number or a letter.

Special Characters

\nThis special character used to add a new line
\rThis special character represents a return
\tThis special character represents a tab
\vThis special character represents a vertical tab
\fThis special character represents a form of feed
\xxxThis special character represents octal characters xxx.
\xhhThis special character represents hex characters hh.

Shorthand character sets

\dThis character is used to match digits from 0 to 9.
\sThis character is used to match all the available spaces, tabs and newlines.
\wThis character is used to match all uppercase and lowercase letters, numbers, and underscores as well.

PHP Regular Expressions Methods

preg_match()

The preg_match() function is used to match an expression as opposed to a string. 

This function requires three main parameters in which we pass an expression, a string, and an array, and then this function works and returns the matched pattern.

Example

<?php
$reg_exp = ("/server/");
$str = 'PHP is a server side scripting language';
if (preg_match($reg_exp, $str)) {
    echo "pattern matched";
} else {
    echo "pattern not match";
}

Code Explanation

In the above code, we used the preg_match() function, firstly we declared the expression or string pattern that we want to match, and then we declared a string. We used the if the condition that will print the “pattern matched” message if it finds a match else it will print the “pattern not matched” message. Check out the results below.

Output

pattern matched

As you can see from the above result it found the pattern in the string, if you want to match all results from a string then see the next method.

preg_match_all()

This function finds all the matches from a string related to a specified pattern, which means if a character is repeated in a string so this function includes that string as well in the output. This function requires the same parameters as the preg_match() method does.

Example

<?php

$reg_exp = ("/PHP/i");
$str = 'PHP is a server side scripting language, php is used to build dynamic applications';

if (preg_match_all($reg_exp, $str,$array)) {
    echo "pattern matched";
} else {
    echo "pattern not match";
}

echo "<pre>";
print_r($array);
echo "<pre>";

?>

Code Explanation

In the above code, we used the preg_match_all() method. Firstly we declared the regular expression (“/PHP/i”) this “i” will match the expression from all uppercase and lower case characters from a string.

In the function, we passed an array as well as a parameter that will show all matched results in the form of an array check out the results below.

Output

pattern matched
Array
(
   
[0] => Array
       
(
            [0] => PHP
            [1] => php
       
)

)

preg_replace()

The preg_replace() method replaces a defined expression with the original expression it founds from the string. This function requires three main parameters, the first is the expression second is replacing value, and the third is the string.

Example

<?php

$reg_exp = ("/client/i");
$org_str = 'PHP is a client side scripting language';
$rep_str ='server';

echo 
preg_replace($reg_exp, $rep_str, $org_str);
?>

Code Explanation

In the above code, we declared three variables. The first one is the regular expression that is the incorrect word in the string, the second variable is the string and the third variable is the word that we want to replace with that incorrect word.

We used the preg_replace() method and passed the above-declared variables as a string. See the results below.

Output

PHP is a server side scripting language

As you can see from the output it replaced the client with the server in the string.

pregi_split()

This function takes a string and the regular expression and splits it then shows the result in the form of an array. This function requires 2 parameters, one is the string and the second is the regular expression.

Example

<?php

$reg_exp = ("/[\s]+/");
$org_str = 'PHP is a client side scripting language';



$spl = preg_split($reg_exp, $org_str);

echo"<pre>";

print_r($spl);

echo "</pre>";

?>

Code Explanation

In the above code, we declared two variables first one is our regular expression and the other one is a string, then we used the preg_split() method and passed those variables as a parameter in it, this function will split the string and will show it in the form of an array. check out the results below.

Output

Array
(
    [0] => PHP
    [1] => is
    [2] => a
    [3] => client
    [4] => side
    [5] => scripting
    [6] => language
)

Conclusion

In this tutorial, we understood the concept of regular expressions in PHP. First of all, we discussed a brief introduction to PHP Regular Expressions, and then we talked about the basic methods and characters we use in Regular Expressions.

We also discussed the way of writing  PHP regular expressions, and in the end, we practiced some examples as well.

That’s all for today hope you like the tutorial if you have any queries regarding this tutorial so feel free to contact us below. Thanks for reading.

Leave a Comment