Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

The preg_match() function

The preg_match() looks for the existence of a pattern in a given string of data. The Syntax for using preg_match() is:

preg_match(pattern_to_match, string_to_search);

If found pattern_to_match is found in string_to_search, preg_match() returns a true value (1) and a false (0) value if not found. Let's take some examples.

In our first example, we will see how one can test to see if, a sentence contains the letters 'php'. We have to account for capitalization by adding the 'i' modifier to the string:

<?php
  $sentence = "It is lots of fun woking with PHP";
	
  if(preg_match("/php/i", $sentence)){
	print "PHP found in sentence";
  } else {
	print "Could not find PHP in the sentence";
  }
?>

The 'i' added at the end of the expression means case insensitive. The pattern being matched (/php/) in this case is compared regardless of the capitalization. The above code would still evaluate to true even if the $sentence only contained the letters "php" within a compound word eg "phping", "phpmonger" and "philiacphp".

If you wanted the test expression to only test "whole words" only and thus not to test the letters 'php' embedded within another word we would have to use the word boundary anchor -> \b. Let's see how, using a different example in which we test for the word 'web'

<?php
  $sentence = "PHP for the web clears all cobwebs and is administered by the webmaster";
  if(preg_match("/\bweb\b/i",$sentence)){
	print "The sentence contains the word web";
  } else {
	print "The sentence does NOT contain the word web";
  }
?>

Notice how the word boundary anchor (\b) is placed on both sides of the word "web".

The above examples may as well have been expressed as...

if($sentence =~/php/i);

... for the fisrt case testing the occurence of the letters "php" and...

if($sentence =~/\bweb\b/i);

... for the second occurence testing for the occurence of the word "web".

<< RegExp Functions | The preg_replace function >>

JamHitz Productions