How to use regular expressions in PHP
Keywords: PHP
Regular expressions are used for processing complex strings in PHP. 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-sensitive and the latter is irrelevant.
Usage:
Ereg (Regular Expression, String, [matching partial array names]);
The regular expressions in PHP3.0 are similar to those in grep.
(2) ereg_replace, eregi_replace
These are replacement functions.
Usage:
Ereg_replace (Regular Expression, replacement string, original string );
The string processing function has a strtr, which is a "Translation" function, similar to tr/.../in Perl /.../.../,
Usage:
Strtr (string, "from", "");
For example:
Strtr ("aaabb", "AB", "cd") returns "cccdd ".
(3) split
It is similar to the explode function, but this time it can be used to split the string where a regular expression is matched.
Usage:
Split (Regular Expression, String, [number of items before removal]);
These functions use regular strings as the first parameter. PHP uses the extended regular string defined by the Posix 1003.2 standard.
For a complete description of Posix regular expressions, see the man page under the regex directory in the PHP software 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 .*/
Ereg ("abc $", $ string );
/* Returns true if "abc" is found at the end of $ string .*/
Eregi ("(ozilla. [23] | MSIE.3)", $ HTTP_USER_AGENT );
/* Returns true if client browser is Netscape 2, 3 or MSIE 3 .*/
Ereg ("([[: alnum:] +) ([[: alnum:] +) ([[: alnum:] +)", $ string, $ regs );
/* Places three space separated words into $ regs [1], $ regs [2] and $ regs [3]. */
Ereg_replace ("^", "", $ string );
/* Put a tag at the beginning of $ string .*/
Ereg_replace ("$", "", $ string );
/* Put a tag at the end of $ string .*/
Ereg_replace ("", "", $ string );
/* Get rid of any carriage return characters in $ string .*/