1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Introduction to Preg in PHP


2 of 5

Preg_Match PHP Function
The Preg_Match PHP function is used to search a string, and return a 1 or 0. If the search was successful a 1 will be returned, and if it was not found a 0 will be returned. Although other variables can be added, it is most simply phrased as: preg_match(search_pattern, your_string). The search_pattern needs to be a regular expression. If you are unfamiliar with them this article gives you an overview of the syntax.

 $data = "I had a box of cerial for breakfast today, and then I drank some juice.";
 if (preg_match("/juice/", $data))
 echo "You had juice.<br>";
 echo "You had did not have juice.<br>";
 if (preg_match("/eggs/", $data))
 echo "You had eggs.<br>";
 echo "You had did not have eggs.<br>";
The code above uses preg_match to check for a key word (first juice then egg) and replies based on whether it is true (1) or false (0). Because it returns these two values it is most often used in a conditional statement.

Related Video
Basic PHP Syntax
Using PHP With HTML
  1. About.com
  2. Technology
  3. PHP / MySQL
  4. PHP Functions
  5. Introduction to Preg - the Preg_match () PHP Function

©2014 About.com. All rights reserved.