复杂html div的正则表达式模式

时间:2013-09-20 16:28:24

标签: php regex

任何想法这个正则表达式可能有什么问题 - 它似乎找不到任何东西:

function ad_content($content) {
    if (is_single()) {
    $find = '#<div id=\"attachment_(\d+)\" class=\"wp-caption aligncenter\" style=\"width: (\d+)px\">(.*?)</div>#s';
    $replace1 = '11111';
    $content = preg_replace($find,$replace,$content,1);
    }
    return $content;
}
add_filter ('the_content','ad_content');

我尝试过像

这样的基本内容
$find = '#attachment#';

这确实有效。

当我使用上述正则表达式时,它不会替换任何内容,也不会出现任何错误。因此,我想它只是找不到任何东西。以下是它应该找到的内容:

<div id="attachment_167" class="wp-caption aligncenter" style="width: 600px"><a href="http://www.url.com"><img class="size-full wp-image-167" alt="text" src="http://www.url.com" width="600" height="776" /></a><p class="wp-caption-text">text &#8211; text</p></div>

我已在this regex validator尝试了它,但确实匹配。

解答:

我想我终于想通了 - the_content hook,似乎并不适用于我的div。就这么简单。

2 个答案:

答案 0 :(得分:1)

你的正则表达式看起来对我来说是真的。

当我将$replace1更改为$replace时,同意稍后在函数中使用,并删除if语句,它似乎有效。那就是:

function ad_content($content) {
    $find = '#<div id=\"attachment_(\d+)\" class=\"wp-caption aligncenter\" style=\"width: (\d+)px\">(.*?)</div>#s';
    $replace = '11111';
    $content = preg_replace($find,$replace,$content,1);
    return $content;
}

似乎按预期工作。我猜测$replace1$replace问题可能不在您执行的代码中(因为您没有检测到任何错误),所以您确定is_single()返回true在你测试它的上下文中?

答案 1 :(得分:0)

您应该使用domparser来获取“正确”div的内容。

想象里面会有一个“div”,或者div iteself可以嵌套:

  <div> 
    Something else
      <div id="thisIwantToMatch"> Foo <div>Bar</div> Baz </div>
    Again something else
  </div>

由于End-Tag不包含属性,因此使用正则表达式找到合适的属性是很困难的。使用“懒惰”正则表达式将匹配<div id="thisIwantToMatch"> Foo <div>Bar</div>,而贪婪的正则表达式将匹配<div id="thisIwantToMatch"> Foo <div>Bar</div> Baz </div>Again something else</div>

显然,这两种情况都不是你想要的。