doujing2017 2012-09-13 00:38
浏览 50
已采纳

HTML标记位置结束preg_replace_callback

Here's a weird wrench that I'm dealing with at the moment. I've been back and forth with it, using a variety of regular expressions, spacing and quote variations but there seems to only be an issue with the placement of the closing </a> tag.

I've built a RegEx parser (I know) to grab tags from HTML output and trigger custom closures for each from a library of what we call "shortcodes". It'll just swap out the tag for the closure's return value, and if the closure doesn't exist, leave the tag in place.

When that </a> is placed on the same line as the tag I'm grabbing, it causes preg_replace_callback to fail. When I add a line break, everything works flawlessly. We're using these tags all over the place as a central part of our template system and they're working wonderfully in every other instance.

So my question is... why?! Is this a bug or am I the bug?

EDIT: Updated pattern to limit reluctancy. Closing </a> tag still kills the process. (@Alan Moore)

EDIT 2: So, the regex was the culprit. It was pulling in the content beyond the tag on the same line on some cases, but this pattern solved the problem - '#\[\s*(\w[^\]\s]*)(.*?)\s*\]#i'.

Failing HTML

<div>
    <a href="[ make_url post_id='200' ]">Some Link</a>
</div>

Successful HTML

<div>
    <a href="[ make_url post_id='200' ]">
        Some Link
    </a>
</div>

or

<div>
    <a href="[ make_url post_id='200' ]">Some Link
    </a>
</div>

PHP

Nothing fancy, and even when I dumb it down to the basics it still fails.

$content = 'HTML output from an output buffer';
//$old_pattern = '#\[\s*?(\w+?(?:\.?\w+?)*?(?=\s|\]))(.+)*?\s*?\]#i';
$pattern = '#\[\s*(\w+(?:\.?\w+)*(?=\s|\]))(.+)\s*\]#i';

$content = preg_replace_callback( $pattern, function( $matches ) {
    // Do things with the matches
}, $content );

// Send content back to the template
return $content;
  • 写回答

2条回答 默认 最新

  • doumalu9257 2012-09-19 13:57
    关注

    It turns out the regex was the culprit. It was pulling in the content beyond the tag on the same line on some cases, but this pattern solved the problem - #\[\s*(\w[^\]\s]*)(.*?)\s*\]#i.

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

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应