Arithmetic operators like +, -, ^
are used by Regular Expressions to create complex expressions. Regular expressions helps in validating email addresses, IP address and so on.
PHP has two types of regular expression functions which can be used as per the requirements
PHP presently has 7 functions to search strings with the help of POSIX Regular Expressions.
Function | Description |
---|---|
ereg() | The function inquires for a string given by a string and returns “true” if the pattern is found, if not false. |
ereg_replace() | The function inquires for a string defined by a pattern and restores the pattern if found. |
eregi() | The function examines throughout a string given for a string by a pattern. The search is not case sensitive. |
eregi_replace() | The function works similar to the ereg_replace(), except search is not case sensitive. |
split() | The function partitions a string into different elements, where every element boundary depends on the occurrence of string pattern. |
spliti() | The function works similar to the split(), except that it is not case sensitive. |
[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.
[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]
[php]
<?php
$copy_date = "Copyright 1999";
$copy_date = preg_replace("([0-9]+)", "2000", $copy_date);
print $copy_date;
?>
[/php]
Output:
[php]
Copyright 2000
[/php]
// 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]
Output:
[php]\$40 for a g3\/400[/php]