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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀