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

How to Convert ereg Regular Expressions to preg in PHP?

Barbara Streisand
Release: 2024-12-20 15:02:14
Original
234 people have browsed it

How to Convert ereg Regular Expressions to preg in PHP?

Conversion from Ereg to Preg in PHP

In PHP, POSIX regular expressions (ereg) have been deprecated since version 5.3.0. To facilitate the transition, it's essential to understand how to convert old ereg expressions to PCRE (Perl Compatible Regular Expressions) (preg).

Syntax Differences

The primary syntax difference is the addition of delimiters in preg. For instance, the following ereg expression:

eregi('^hello world');
Copy after login

should be converted to a preg_match expression like this:

preg_match('/^hello world/', $str);
Copy after login

The delimiters can be various non-alphanumeric characters, with common choices being ~, /, and #.

Matching Brackets

Additionally, you can use matching brackets as delimiters:

preg_match('[^hello]', $str);
preg_match('(^hello)', $str);
preg_match('{^hello}', $str);
Copy after login

Escaping Delimiters

If your delimiter appears in the regular expression, escape it using a backslash:

eregi('^/hello', $str);
preg_match('/^\/hello/', $str);
Copy after login

To escape all delimiters and reserved characters, use preg_quote:

$expr = preg_quote('/hello', '/');
preg_match('/^'.$expr.'/', $str);
Copy after login

Modifiers

PCRE supports modifiers for various features. For instance, the case-insensitive modifier i replaces the eregi function:

eregi('^hello', 'HELLO');
preg_match('/^hello/i', 'HELLO');
Copy after login

Example Conversion

In your provided example, a regular expression is not necessary. Instead, you can use the following PHP function:

stripos($str, 'hello world') === 0
Copy after login

The above is the detailed content of How to 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