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

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

问题描述

由于自PHP 5.3.0起不推荐使用 POSIX正则表达式(ereg),因此,我想知道将旧表达式转换为 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.

相关:

  • How to change PHP's eregi to preg_match
  • Changing ereg_replace to equivalent preg_replace

推荐答案

语法上的最大变化是添加了

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 :

$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');

您可以在手册中找到对 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天全站免登陆