如何使用PHP正则表达式将属性添加到第一个P标记? [英] How to add attribute to first P tag using PHP regular expression?

查看:268
本文介绍了如何使用PHP正则表达式将属性添加到第一个P标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


< p>帖子的第一段< / p>
< p>帖子的第二段< / p>

为了让我在第一段的酷炫风格(这是其中的一件事)我需要挂钩到get_posts函数中,用preg_replace过滤输出。



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

 < h2>某些标题< / h> 
< p class =first>帖子的第一段< / p>
< p>帖子的第二段< / p>

到目前为止我还没有这样做,但它甚至没有工作(错误是:preg_replace()[function

  $ output = preg_replace('< p [^> ] *>','< p class =first>',$ content); 

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

解决方案

通过阅读答案,有一些方法可行,但都有缺点,无论是使用外部解析库还是可能匹配标签而不是P标签或匹配其属性。
$ b

我最终使用了这个解决方案,使用 here

  str_replace_once('< p> ;','< p class =first>',$ content); 

足够简单,它可以像预期的那样工作。这是完整的WordPress代码片段,可以在调用the_content()时随时过滤第一段:

  add_filter('the_content','first_p_style ); 
函数first_p_style($ content){
$ output = str_replace_once('< p>','< p class =first>',$ content);
return($ output);
}

感谢您的所有答案!


WordPress spits posts in this format:

<h2>Some header</h>
<p>First paragraph of the post</p>
<p>Second paragraph of the post</p>
etc.

To get my cool styling on the first paragraph (it's one of those things that looks good only sparingly) I need to hook into the get_posts function to filter its output with a preg_replace.

The goal is to get the above code to look like:

<h2>Some header</h>
<p class="first">First paragraph of the post</p>
<p>Second paragraph of the post</p>

I have this so far but it's not even working (the error is: "preg_replace() [function.preg-replace]: Unknown modifier ']'")

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

I can't use CSS3 meta-selectors because I need to support IE6, and I can't apply the :first-line meta-selector (this is one that IE6 supports) on the parent container because it would hit the H2 instead of the first P.

解决方案

Reading through the answers there are some that will work but all have drawbacks of either using an external parsing library or possibly matching tags other than the P tag or also matching its attributes.

I ended up using this solution with the str_replace_once function from here:

str_replace_once('<p>', '<p class="first">', $content);

Simple enough and it works just as intended. Here's full WordPress code snippet to filter the first paragraph any time the_content() is called:

add_filter('the_content', 'first_p_style');
function first_p_style($content) {
 $output=str_replace_once('<p>', '<p class="first">', $content);
 return ($output);
}

Thanks for all the answers!

这篇关于如何使用PHP正则表达式将属性添加到第一个P标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆