dsds661730652211 2010-02-07 09:35
浏览 61
已采纳

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

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.

  • 写回答

5条回答 默认 最新

  • duanmengmiezen8855 2010-02-07 18:04
    关注

    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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?