Using POSIX Regular Expressions


Searching for a match with POSIX regular expressions is done using the ereg() function. You provide a pattern, a string to search, and a variable name that receives the results as an array. The first element in this array is the complete match; the next elements are all matched subpatterns (defined in parentheses), from inner patterns to outer patterns, from left to right. The preceding code shows this, using the function phpversion() that returns the installed version of PHP. See Figure 1.4 for the output of this script when using PHP 5.0.4.

Searching in Strings Using POSIX Regex (ereg.php)
 <?php   $string = 'This site runs on PHP ' . phpversion();   ereg('PHP (([0-9])\.[0-9]\.[0-9]+)',     $string, $matches);   vprintf('Match: %s<br /> Version: %s; Major: %d.',     $matches); ?> 

Figure 1.4. Splitting the PHP version using regular expressions.


The + symbol after the last [0-9] expression in this example takes care of PHP versions like 4.3.11. If you do not want the search to be case sensitive, append an i to the function name: eregi().

TIP

The return value of ereg() is a Boolean that can be used to find out whether there was a match:

 if (ereg($pattern, $string)) {   echo 'Match found.' } 





PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net