preg_match捕获的意外子模式

时间:2012-08-10 09:38:53

标签: preg-match pcre

我在php中使用preg_match();

进行一些正则表达式

我的文字看起来像这样:

 $imy = "...without sophisticated apparatus<div class="caption"><div class="caption-inner">
 <img src="http://dev.mysite.org/Heatmap.png" alt="" title="" class="image-thumbnail" />
 Caption text</div></div>Some more text...
 <img src="http://dev.mysite.org/Heatmap.png" alt="" title="" class="image-thumbnail" />blablah..."

我的目标是选择“div”标签中包含的“img”标签(包括“div”标签),或者如果它没有包含在div中,则选择“img”。我也在每种情况下都想捕获“img”标签的src属性中包含的地址。

这是我使用的模式:

$imagepattern = '/<div class="caption-inner[^>]+>.*<img\b[^>]*\bsrc="([^">]*)"[^>]*>.*<\/div>(<\/div>)?|<img\b[^>]*\bsrc="([^">]*)"[^>]*>/Us';

它适用于“div”封闭图像,但对于divless图像,我得到了捕获子模式的奇怪结果。

我迭代地调用preg_match并从主题字符串中删除匹配,然后再将其重新发送到preg_match。我对preg_match的调用如下:

preg_match($imagepattern,$imy,$image,PREG_OFFSET_CAPTURE)

在与divless图像标记匹配时,我在图像数组中得到的内容如下所示:

$image = [0] => Array
        (
            [0] => <img src="http://dev.molmeth.org/Heatmap.png" alt="" title="" class="image-thumbnail" />
            [1] => 1
        )

    [1] => Array
        (
            [0] =>
            [1] => -1
        )

    [2] => Array
        (
            [0] =>
            [1] => -1
        )

    [3] => Array
        (
            [0] => http://dev.mysite.org/Heatmap.png
            [1] => 11
        )

$ image数组如何拥有'2'和'3'键?我不只有一个子模式吗?这是不是因为模式中的'或'条件?

1 个答案:

答案 0 :(得分:0)

在你的preg_match表达式中,你有3个捕获组。

整个表达式匹配因为或(因为你搜索div包含图像或divless图像)

对于divless图像,只有捕获组3将填充数据和捕获组1&amp; 2将是空的。

相关问题