php preg_match 和 ereg 语法差异

2023-12-14

我发现语法是preg_match()和已弃用的ereg()是不同的。
例如:

我以为

preg_match('/^<div>(.*)</div>$/', $content);

意思是一样的

ereg('^<div>(.*)</div>$', $content);

但是我错了。preg_match()不包含特殊字符,如输入ereg() does.

所以我开始使用这个语法:

preg_match('/^<div>([^<]*)</div>$/', $content);

但它与我需要的并不完全相同。

谁能建议我如何在不使用已弃用的函数的情况下解决这个问题?


对于解析 HTML 我建议阅读这个问题并选择内置的 PHP 扩展。

如果由于某种原因你need or want要使用 RegEx 来做到这一点,您应该知道:

  • preg_match() is a greedy little bugger and it will try to eat your anything (.*) till it get's sick (meaning it hits recursion or backtracking limits). You change this with the U modifier1.

  • the engine expects to be fed a single line. You change this with the m or s modifiers1.

  • 使用你的'不是 ' ([^<]*)hack 做得很好,因为它强制引擎首先停止<字符,但会起作用only if the <div>里面不包含其他标签!

ref: 1 PCRE Pattern Modifiers

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

php preg_match 和 ereg 语法差异 的相关文章

随机推荐