如何在 PHP 中将 ereg 表达式转换为 preg? [英] How can I convert ereg expressions to preg in PHP?

查看:21
本文介绍了如何在 PHP 中将 ereg 表达式转换为 preg?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 POSIX 正则表达式 (ereg) 自 PHP 5.3.0 起已弃用,我想知道将旧表达式转换为 PCRE(Perl 兼容正则表达式)(preg) 的简单方法.

Since POSIX regular expressions (ereg) are deprecated since PHP 5.3.0, I'd like to know an easy way to convert the old expressions to PCRE (Perl Compatible Regular Expressions) (preg).

例如,我有这个正则表达式:

Per example, I have this regular expression:

eregi('^hello world');

如何将表达式转换为 preg_match 兼容的表达式?

How can I translate expressions into preg_match compatible expressions?

注意:这篇文章用作所有与从 ereg 到 preg 转换相关的文章的占位符,并作为相关问题的重复选项.请不要关闭此问题.

Note: This post serves as a placeholder for all posts related to conversion from ereg to preg, and as a duplicate options for related questions. Please do not close this question.

相关:

推荐答案

语法上最大的变化是增加了 分隔符.

The biggest change in the syntax is the addition of delimiters.

ereg('^hello', $str);
preg_match('/^hello/', $str);

分隔符几乎可以是任何非字母数字、反斜杠或空格字符.使用最多的一般是~/#.

Delimiters can be pretty much anything that is not alpha-numeric, a backslash or a whitespace character. The most used are generally ~, / and #.

您也可以使用匹配的括号:

You can also use matching brackets:

preg_match('[^hello]', $str);
preg_match('(^hello)', $str);
preg_match('{^hello}', $str);
// etc

如果在正则表达式中找到你的分隔符,你必须将它转义:

If your delimiter is found in the regular expression, you have to escape it:

ereg('^/hello', $str);
preg_match('/^/hello/', $str);

您可以使用 preg_quote 轻松转义字符串中的所有分隔符和保留字符:

You can easily escape all delimiters and reserved characters in a string by using preg_quote:

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

此外,PCRE 支持 修饰符 用于各种事情.最常用的修饰符之一是不区分大小写的修饰符 i,它可以替代 eregi:

Also, PCRE supports modifiers for various things. One of the most used is the case-insensitive modifier i, the alternative to eregi:

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

您可以在手册中找到PHP 中的PCRE 语法的完整参考,以及 POSIX 正则表达式和 PCRE 之间的差异列表帮助转换表达式.

You can find the complete reference to PCRE syntax in PHP in the manual, as well as a list of differences between POSIX regex and PCRE to help converting the expression.

但是,在您的简单示例中,您不会使用正则表达式:

However, in your simple example you would not use a regular expression:

stripos($str, 'hello world') === 0

这篇关于如何在 PHP 中将 ereg 表达式转换为 preg?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆