Converting PCRE Expressions with PHP
POSIX regular expressions (ereg) are no longer recommended in PHP 5.3.0 and later. This article provides an easy way to convert old ereg expressions to Perl Compatible Regular Expressions (PCRE or preg), which are still supported.
Syntax Changes
The primary difference to note is the addition of delimiters in preg. They prevent collisions with characters within the expression. Common delimiters include ~, /, and #.
Escaping Delimiters
If the delimiter occurs within the expression, it must be escaped. For instance, an expression that contains a forward slash requires escaping:
preg_match('/^\/hello/', $str);
Using preg_quote
To ensure escape characters are properly added, use the preg_quote function. It escapes all delimiters and reserved characters:
$expr = preg_quote('/hello', '/'); preg_match('/^'.$expr.'/', $str);
Case-Insensitivity
The i modifier provides case-insensitive matching like eregi:
preg_match('/^hello/i', 'HELLO');
Reference Guide
For a comprehensive reference on PCRE syntax in PHP, consult the official manual. Additionally, the manual includes a breakdown of the differences between POSIX and PCRE regex, aiding in the conversion process.
Simpler Alternative for Simple Expressions
In the provided example (matching 'hello world' at the start of a string), a regular expression might be unnecessary:
stripos($str, 'hello world') === 0
The above is the detailed content of How Can I Easily Convert My PHP ereg Regular Expressions to PCRE?. For more information, please follow other related articles on the PHP Chinese website!