Home > Backend Development > PHP Tutorial > How Can I Effectively Convert ereg Regular Expressions to preg in PHP?

How Can I Effectively Convert ereg Regular Expressions to preg in PHP?

Susan Sarandon
Release: 2025-01-03 22:19:40
Original
336 people have browsed it

How Can I Effectively Convert ereg Regular Expressions to preg in PHP?

Converting ereg Regular Expressions to preg in PHP

As PHP 5.3.0 deprecates POSIX regular expressions (ereg), converting old ereg expressions to PCRE (Perl Compatible Regular Expressions) (preg) becomes essential. This article provides a simplified guide to facilitate this transition.

Unlike ereg, preg requires delimiters at both ends of the regular expression. Commonly used delimiters include ~, /, and #. For instance, the ereg expression "^hello world" can be converted to preg_match("/^hello world/") by enclosing it within forward slashes.

Matching brackets can also serve as delimiters, allowing variations like 1, (^hello), and {^hello}. However, delimiters included in the expression must be escaped using a backslash. Example: ereg("^/hello", $str) becomes preg_match('/^/hello/', $str).

preg_quote function proves useful in escaping delimiters and reserved characters in a string. Example: $expr = preg_quote('/hello', '/'); preg_match('/^'.$expr.'/', $str).

PCRE supports modifiers like i (case-insensitive), equivalent to eregi. Example: eregi('^hello', 'HELLO') can be replaced with preg_match('/^hello/i', 'HELLO').

For detailed PCRE syntax references and ereg-PCRE conversion guidance, consult the PHP manual.

In some cases, regular expressions may not be necessary. For the example provided (eregi('^hello world')), a simplified comparison using stripos($str, 'hello world') === 0 can suffice.


  1. hello

The above is the detailed content of How Can I Effectively Convert ereg Regular Expressions to preg in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template