使用 preg match 和 Replace 来替换 ol 标签中的 li 标签
这是我得到的:
<ol>
<li></li>
<li></li>
</ol>
<ul>
<li></li>
<li></li>
</ul>
if (preg_match("/<ol>.*(<li(|\s*\/)>).*<\/ol>/Ums", $text->Bodytext)) {
$cleanlist = preg_replace("/(<li(|\s*\/)>)/", "<li><tag>", $text->Bodytext);
如果页面仅包含 ol 标签,则此 php 代码运行良好,但如果它由于某种原因同时包含 ul 和 ol 标签,它也会更改 ul 标签内的 li 标签,我只希望它在 ol 标签内替换它。可能是什么问题以及如何解决它?
Here is what i got:
<ol>
<li></li>
<li></li>
</ol>
<ul>
<li></li>
<li></li>
</ul>
if (preg_match("/<ol>.*(<li(|\s*\/)>).*<\/ol>/Ums", $text->Bodytext)) {
$cleanlist = preg_replace("/(<li(|\s*\/)>)/", "<li><tag>", $text->Bodytext);
This php code works well if the page only contains ol tags, but if it contains both ul and ol tags for some reason it changes li tags inside ul tags too and I only want it to replace it within ol tags. What could be the problem and how can i fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的正则表达式中的问题可能是贪婪。您应该在
.*?
后附加一个问号,以便它匹配更少的填充。然而,如果您没有尝试使用单个正则表达式来完成它,那么它会更可靠。这总是比走简单的路线更复杂一些:
现在,在模因海报出现之前,使用正则表达式并不是最可靠的方法。除非你有古怪的 HTML,否则它在你的情况下是可行的。另一种方法是使用 phpQuery 或 QueryPath 但是,匹配非常简单如
qp($html)->find("ol")->find("li")
。尽管实际的替换会更多地涉及这种方法。The problem in your regex is likely the greedyness. You should append a question mark to
.*?
so it matches less padding.It would however be more reliable it you didn't try to accomplish it with a single regex. That's always a bit more involving then going the simple route:
Now before the meme posters come around, using regular expressions is not the most reliable approach. It's workable in your case unless you have wacky HTML. An alternative would be to use phpQuery or QueryPath however, where matching is as simple as
qp($html)->find("ol")->find("li")
. Though the actual replacing would be more involving with that approach.在 PHP 5.3 中,可以按如下方式完成此任务:
输出为:
In PHP 5.3 this task could be done as follows:
The output would be: