1. Home
  2. Computing & Technology
  3. PHP / MySQL

Introduction to Preg in PHP

By , About.com Guide

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.

Explore PHP / MySQL
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. PHP Functions
  5. Preg_Match - Preg Match PHP - PHP Function Preg_Match

©2009 About.com, a part of The New York Times Company.

All rights reserved.