php - 如何在 PHP 中将 ereg 表达式转换为 preg?

标签 php preg-replace preg-match pcre ereg

由于 POSIX regular expressions (ereg) 自 PHP 5.3.0 起已弃用,我想知道一种将旧表达式转换为 PCRE (Perl Compatible Regular Expressions) (preg) 的简单方法。

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

eregi('^hello world');

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

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.

Related:

最佳答案

语法上最大的变化是增加了delimiters .

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

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

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

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

如果在正则表达式中找到您的分隔符,则必须对其进行转义:

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

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

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

另外,PCRE 支持 modifiers对于各种事情。最常用的修饰符之一是不区分大小写的修饰符 i,它是 eregi 的替代品。 :

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

您可以找到对 PCRE syntax in PHP in the manual 的完整引用。 ,以及 list of differences在 POSIX 正则表达式和 PCRE 之间进行转换,以帮助转换表达式。

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

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

关于php - 如何在 PHP 中将 ereg 表达式转换为 preg?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6270004/

相关文章:

php - 用正则表达式确定字符串的结构

php - 我可以将哪些服务器端 PDF 呈现组件与 .NET、PHP、Ruby 等一起使用?

php - preg_replace 仅外部标签? (...我们不是在谈论完整的 'html parsing' ,只是一些 Markdown )

php - 在 php 中使用正则表达式将每个前导和尾随空格替换为下划线

javascript - Replace() 标签在 JavaScript 中不起作用

php - 在 wordpress 中的帖子之间切换

php - 即使 strlen 在可接受的范围内,此正则表达式也会截断字符串中的最后一个单词

php - 使用 preg_match() 查找与模式匹配的子串的开始/停止位置

php - 如果某个字符串在 PHP 中匹配,则在回显某些文本时使函数发生

php - 正则表达式错误 preg_replace_callback() : Unknown modifier '.' in