duanjing7651
duanjing7651
2016-01-02 12:13

wordpress中的preg_replace在html标签处停止

I have written a preg_replace in my functions.php for my wordpress blog for my girlfriend to use a "shortcode" like the following:

[spoiler id="1" show="show me the list" hide="hide the list"]test1
test2<ul>test3
  <li>list item 1</li>
  <li>list item 2</li>
</ul>
[/spoiler]

My preg_replace in the functions.php is the following:

function BUFU_add_spoilers ($content)
{   global $post;
    $pattern = "/\[spoiler id=\"(.*?)\" show=\"(.*?)\" hide=\"(.*?)\"\](.*?)\[\/spoiler\]/is";
    $replacement ='<br><div align="right" style="margin: -58px 0 0 0"><a id="button_show_%SPOILID%_$1" onclick="document.getElementById(\'spoiler_%SPOILID%_$1\').style.display=\'block\'; document.getElementById(\'button_hide_%SPOILID%_$1\').style.display=\'\'; document.getElementById(\'button_show_%SPOILID%_$1\').style.display=\'none\';"><h5>[$2]</h5></a></div><div align="right"><a id="button_hide_%SPOILID%_$1" style="display: none" onclick="document.getElementById(\'spoiler_%SPOILID%_$1\').style.display=\'none\'; document.getElementById(\'button_hide_%SPOILID%_$1\').style.display=\'none\'; document.getElementById(\'button_show_%SPOILID%_$1\').style.display=\'\';"><h5>[$3]</h5></a></div><span id="spoiler_%SPOILID%_$1" style="display: none" class="spoilerBox">$4</span>';
    $content = preg_replace($pattern, $replacement, $content);
    $content = str_replace("%SPOILID%", $post->ID, $content);
    return $content;
}
add_filter('the_content', 'BUFU_add_spoilers', 5);

All works just fine if there is only text in between the "shortcodes", but it somehow does not work for the example above. The spoiler will include everything up to the opening "<ul>" (or an opening "<table>" for that matter), so test1 and test2 are in the spoiler, test3 is NOT. I just have no idea why. I tested the preg_replace online and it worked just fine.

I reckon it has something to do with the way wordpress adds filters and stuff to work on the text, but I can't figure it out... The result is just an empty ... class="spoilerBox"></span> followed by the list..

If anyone can help me with this, it would be greatly appreciated! I'm really going nuts over this problem!

Thanks in advance,

BUFU

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongqiu5184 dongqiu5184 3年前

    Just to close this:

    Simply use shortcodes instead.

    wordpress reference for add_shortcode

    点赞 评论 复制链接分享

为你推荐