Perl-Compatible regular expressions are more powerful than the POSIX. Following are the PHP PCRE functions to search strings.
The function preg_match() examines the string for a pattern. If found, returns true and false if not.
[php]
<?php
$my_url = "www.splessons.com";
if (preg_match("/splessons/", $my_url))
{
echo "the url $my_url contains splessons";
}
else
{
echo "the url $my_url does not contain splessons";
}
?>
[/php]
Output:
[php]the url www.splessons.com contains splessons[/php]
In the above example,
=>
preg_match()
is the PHP Regular Expression function
=>
'/splessons/'
is the Regular Expression pattern that has to be matched
=>
$my_url
is the variable containing the text to be matched against.
The function splits string by a regular expression.
[php]
<?php
// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords = preg_split("/[\s,]+/", "SPLessons PHP, Tutorial");
print_r($keywords);
?>
[/php]
Output:
[php]
Array (
[0] => SPLessons
[1] => PHP
[2] => Tutorial
)[/php]
The function preg_replace() works similar to the function ereg_replace(), except that the expressions can be used in the pattern and replacement input parameters.
[php]
<?php
$copy_date = "Copyright 1999";
$copy_date = preg_replace("([0-9]+)", "2000", $copy_date);
print $copy_date;
?>
[/php]
Output:
[php]
Copyright 2000
[/php]
The function preg_grep() examines every element of input_array and returns the elements that matches with the regular expression pattern.
[php]
<?php
$foods = array("pasta", "steak", "fish", "potatoes");
// find elements beginning with "p", followed by one or more letters.
$p_foods = preg_grep("/p(\w+)/", $foods);
print "Found food is " . $p_foods[0];
print "Found food is " . $p_foods[1];
?>
[/php]
Output:
[php]
Found food is pastaFound food is
[/php]
The function preg_ quote() helps to quote characters of regular expressions.
[php]
<?php
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
echo $keywords; // returns \$40 for a g3\/400
?>
[/php]
Output:
[php]\$40 for a g3\/400[/php]