How to use regular expressions in PHP
Keywords: PHP
In PHP, regular expressions are used to process complex strings. The supported regular expressions are as follows:
ereg()
ereg_replace()
eregi()
eregi_replace()
split()
(1) ereg, eregi
This is a regular expression matching function. The former is case-related matching, while the latter is irrelevant.
Usage:
ereg(regular expression, string, [match part of the array name ]);
Regular expressions in PHP3.0 are roughly similar to those used in grep.
(2)ereg_replace, eregi_replace
These are replacement functions.
Usage:
ereg_replace(regular Expression, replacement string, original string);
There is a strtr in the string processing function, which is a "translation" function, similar to tr/.../.../ in Perl,
Usage:
strtr(string, "from", "to");
For example:
strtr("aaabb","ab","cd") returns "cccdd".
(3) split
is somewhat similar to the explode function, but this time you can split the string where it matches a certain regular expression.
Usage:
split (regular expression, string, [remove the first number of items]) ;
These functions all use regular strings as the first parameter. PHP uses extended regular strings as defined by the Posix 1003.2 standard.
For a complete description of Posix regular expressions, please see the man page in the regex directory of the PHP package.
Regular expression examples:
ereg("abc",$string);
/* Returns true if "abc" is found anywhere in $string. */
ereg("^abc",$string);
/* Returns true if "abc" is found at the beginning of $string. */