By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

If preg_match syntax

How to check if a match was found using if preg_match, returning either 0 or 1.

Created: 2011-10-22 12:29

If you want to check if a match was found in any given string, simply include the preg_match in an if statement.

if (preg_match("/Brugbart/i", "Tutorial and References - Welcome to Brugbart")) {
    echo "Match found.";
} else {
    echo "Nothing was found.";
}

The if will either return 1 or 0, depending on whether a match was found or not, where 1 will be success.

Another way to check, would be to use the Identical (===) operator.

if (preg_match("/Brugbart/i", "Tutorial and References - Welcome to Brugbart") === 1) {
    echo "Match found.";
} else {
    echo "Nothing was found.";
}

This is to avoid conflicts, because even though its unlikely, preg_match will return false on error. Had we only used the Equal (==) operator, it could be mistaken for nothing was found, in cases where an error occurred.