如何使用PHP正则表达式将属性添加到第一个P标记?

Rod*_*oev 2 html php regex

WordPress以这种格式吐出帖子:

<h2>Some header</h>
<p>First paragraph of the post</p>
<p>Second paragraph of the post</p>
etc.
Run Code Online (Sandbox Code Playgroud)

为了在第一段(这是那些看起来很好看的东西之一)上获得我很酷的样式,我需要挂钩到get_posts函数以使用preg_replace过滤其输出.

目标是让上面的代码看起来像:

<h2>Some header</h>
<p class="first">First paragraph of the post</p>
<p>Second paragraph of the post</p>
Run Code Online (Sandbox Code Playgroud)

到目前为止,我有这个,但它甚至没有工作(错误是:"preg_replace()[function.preg-replace]:未知的修饰符']'")

$output=preg_replace('<p[^>]*>', '<p class="first">', $content);
Run Code Online (Sandbox Code Playgroud)

我不能使用CSS3元选择器,因为我需要支持IE6,我不能在父容器上应用:第一行元选择器(这是IE6支持的),因为它会击中H2而不是第一个P.

Bri*_*new 6

您可能会发现使用HTML解析器(例如解析器)更容易,更可靠.众所周知,HTML使用正则表达式可靠地解析(技术上,不可能),并且解析器将为您提供一种非常简单的方法来查找您感兴趣的节点.文档的第一页有一个标签为"如何修改"的选项卡HTML元素".