PHP RegEx Functions

PHP RegEx Functions

PHP provides a set of highly optimized functions to utilize Regular Expressions. These functions all begin with preg_ (which stands for PCRE - Perl Compatible Regular Expressions).


1. Using preg_match()

The preg_match() function will tell you whether a string contains matches of a pattern. It returns 1 if a match is found, and 0 if not.

Example

<?php
$str = "Welcome to IntricateDevo";
$pattern = "/intricate/i";

echo preg_match($pattern, $str); // Outputs 1 ?>

2. Using preg_match_all()

The preg_match_all() function will tell you how many matches were found for a pattern in a string.

Example

<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";

echo preg_match_all($pattern, $str); // Outputs 4 ?>

3. Using preg_replace()

The preg_replace() function will replace all of the matches of the pattern in a string with another string.

Example

<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";

echo preg_replace($pattern, "IntricateDevo", $str); // Outputs "Visit IntricateDevo!" ?>