1. Computing
Send to a Friend via Email

Introduction to Preg in PHP

By

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>";
 }
 else
 {
 echo "You had did not have juice.<br>";
 }
 if (preg_match("/eggs/", $data))
 {
 echo "You had eggs.<br>";
 }
 else
 {
 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

©2014 About.com. All rights reserved.