PHP Free Tutorial

Regular Expression in PHP

In PHP, Programming by Baqir Ali

When a user fills out a form, you might want to verify that the format was correct before sending the data to a database. For example, did the user enter a valid birthdate, e-mail address, or credit card number? This is where regular expressions enter the picture. Their power is great therefore other programming languages also use this for text,  for performing refined searches and replacements,  capturing subpatterns in strings, testing input data for certain characters, and more.

What is a regular expression?

So, what is a regular expression? A regular expression is really just a sequence or pattern of characters as a result we match them against a string of text when performing searches. When you create a regular expression, you test the regular expression against a string. The regular expression is enclosed in forwarding slashes. For example, the regular expression /green/ might be matched against the string “The green grass grows”. If green is contained in the string, there is a successful match. Like Perl, PHP also provides a large variety of regular expression metacharacters to control the way a pattern is found; for example, the regular expression /^[Gg]reen/ consists of a caret and a set of square brackets. These metacharacters control the search so that the regular expression matches only strings starting with an upper- or lowercase letter g. The possibilities of fine-tuning your search with regular expressions and their metacharacters are endless.

Where do we use Regular Expression in PHP?

PHP regular expressions are used primarily to verify data on the server-side. When a user fills out a form and presses the submit button, the form is sent to a server, and then to a PHP script for further processing.

Why not handle

Although it is more efficient to handle form validation on the client-side with programs like Javascript or JScript, these programs might be disabled, or might not be programmed to verify form data. Checking the form on the client-side allows for instant feedback, and less traveling back and forth between the browser and server, but to ensure that the data has been verified, PHP can recheck it. Once the user has filled out a form and submitted it, PHP can check to see if all the boxes have been filled out correctly, and if not, the user is told to reenter the data before the form data is processed. With the power provided by regular expressions, the ability to check for any type of input, such as e-mail addresses, passwords, social security numbers, birthdates, and so on, is greatly simplified. You can also use regular expressions to complete complex search and replace operations in text files, processes that would be difficult, if not impossible, with PHP’s standard string functions.

Types of regular expression in PHP

  • POSIX
  • Perl Style

What is POSIX regular expression in PHP

The first set of functions (POSIX style) are those prefixed with ereg_. They behave much like the traditional UNIX egrep command. The advantage of the ereg functions is that they are supported by the oldest versions of PHP.

What is Perl Style regular expression in PHP

The second set of regular expression functions (Perl style) start with preg_. These functions mimic Perl’s regular expressions and support the newer features, such as backreferences, capturing, look ahead, and look behind. These functions are only available if your version of PHP supports the PCRE (Perl Compatible Regular Expression) library, and the PCRE library is installed on your Web server so you can check the phpinfo() output from your first test scripts to see if PCRE is enabled

Perl is a popular powerful scripting language known for its ability to manipulate and extract text. It supports regular expressions and regular expression metacharacters to make pattern matching relatively easy and quick. PHP has mimicked Perl by providing special functions to handle pattern matching and included Perl’s metacharacters for pattern matching. We discuss each of the pattern-matching functions before delving into regular expression metacharacters.

FunctionWhat it does?
preg_grep()Returns an array of patterns that matched
preg_match()Performs the match
preg_match_all() Performs the global match
Preg_replace()Searches for a pattern and replaces it with another one
preg_split()Splits up a string into substrings using regular expression

Finding a pattern in PHP

We will use both functions preg_match() and preg_match_all()

  • Both used to find a pattern in a string
  • preg_match() only finds the first occurrence
  • preg_match_all() finds all the occurrences

Example 1:

<?php
$string = "My gloves are worse love for wear";
$reg = "/love/";
$result = preg_match($reg, $string, $matches);

echo("result = $result<br/>"); 
echo "Contents of matches <br>"; 
echo("<pre>"); 
print_r($matches); echo("</pre>");

?>

Output:

result = 1
Contents of matches
Array
(
    [0] => love
)

Example 2:

<?php
$string = "My gloves are worse love for wear";
$reg = "/(love) for (wear)/";
$result = preg_match($reg, $string, $matches);

echo("result = $result<br/>"); 
echo"Contents of matches<br/>";
 echo("<pre>"); print_r($matches); echo("</pre>");

?>

Output:

result = 1
Contents of matches
Array
(
    [0] => love for wear
    [1] => love
    [2] => wear
)

Example 3:

<?php
$data = "Codemodes the ultimate online learning plateform.";

$reg = "/Codemodes/";
$result = preg_match_all($reg, $data, $matches, PREG_OFFSET_CAPTURE);

echo("Result = $result<br/>");

echo("<pre>");
print_r($matches);
echo("</pre>");

?>

Output:

Result = 1
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Codemodes
                    [1] => 0
                )

        )

)

Search and Replace in PHP

Searches for a pattern in the subject and replaces the subject with something else using preg_replace().

Example 4:

<?php
$old_string = "I live in New Orleans.";
print ("Original string: <em>$old_string</em><br />");
$reg = "/New Orleans/";
$rep_string = "Philadelphia";

$new_string	=	preg_replace($reg,	$rep_string,
$old_string);

print("After replacement<br/>");
print ("Original string: <em>$old_string</em><br />"); print ("New string: <em>$new_string</em><br />");


?>

Output:

Original string: I live in New Orleans.
After replacement
Original string: I live in New Orleans.
New string: I live in Philadelphia.

Splitting in PHP using regular expression

array preg_split ( string pattern, string subject [, int limit [,int flags]] )

  • pattern – to find
  • subject – to search
  • limit – how many splits, -1 is no limit

Splits up a string by some delimiter that marks the separation between the words in the string, such as a space or a colon or a combination of such characters therefore the function returns an array of substrings.

If a limit is specified, then only that many substrings are returned.

If you are using a single character or simple string as the delimiter, the explode() function is faster

Example 5:

<?php
$string="apples#oranges#peaches";
$array=preg_split("/#/", $string); // Split by # echo("<pre>");
print_r($array); 
echo("</pre>");

?>

Output:

Array ( [0] => apples [1] => oranges [2] => peaches )

Example 6: Multiple Delimeters

<?php
$colors="Primary:red,yellow,blue;Secondary:violet,oran ge,green";
$array=preg_split("/[:,;]/", $colors); echo "<h2>Splitting Colors</h2>"; echo("<pre>");
print_r($array); echo("</pre>");
foreach ($array as $key=>$value)
{
if ($value == "Primary" || $value == "Secondary")
{
 
}
else
{

}
}
 
print "$value<br />"
print "\t$key: $value<br />";
?>

Output:

Splitting Colors
Array
(
    [0] => Primary
    [1] => red
    [2] => yellow
    [3] => blue
    [4] => Secondary
    [5] => violet
    [6] => oran ge
    [7] => green
)
green
7: green

Example 7:

<?php

$alpha="SAN FRANCISCO";
$array =	preg_split("//", $alpha, 3, PREG_SPLIT_NO_EMPTY);
$array=preg_split("//", $alpha, -1, PREG_SPLIT_NO_EMPTY); // -1 is the number of splits, -
//1 means no limit, 2 means only two splits
echo "<h2>Splitting A Word into Letters</h2><pre>"; print_r($array);
echo("</pre>");


?>

Output:

Splitting A Word into Letters
Array
(
    [0] => S
    [1] => A
    [2] => N
    [3] =>  
    [4] => F
    [5] => R
    [6] => A
    [7] => N
    [8] => C
    [9] => I
    [10] => S
    [11] => C
    [12] => O
)

Support us by sharing this post