【问题标题】:PHP regex subgroups cannot be captured无法捕获 PHP 正则表达式子组
【发布时间】:2018-08-20 10:53:13
【问题描述】:

我有一个正则表达式模式,预计会从一些 <img> html 中捕获 srcheight(可能在 heightstyle 属性中)元素。这是我的模式:

/img[^\>]*(?:height="([\d]+)")?[^\>]*src="([^"]+)"[^\>]*(?:style\="height:([\d]+)px;?[^"]+")?[^\>]*/i

我使用preg_match_all函数搜索以下字符串:

<img alt="" height="200" src="http://www.example.com/example.png" width="1500" style="height:200px;" />

src 没有问题,但它无法捕获 height 子组。我的正则表达式模式错了吗?

【问题讨论】:

  • 这称为解析。不要使用正则表达式来解析 HTML 文档。请改用 DOM 解析器。
  • 因为height 组后面跟着?,所以它变成了可选的。它前面的[^\&gt;]* 子表达式是贪婪的,匹配到src= 之前的所有内容。顺便说一句,&gt; 不是特殊的正则表达式字符,不需要转义。 = 也是如此。阅读 PHP PCRE 中的 meta charactersrepetition,然后去掉 regex(如果属性顺序不同,则不匹配)和 use a DOM parser to parse HTML fragments

标签: php regex preg-match-all


【解决方案1】:

如果您可以选择,您可以使用 DOM 而不是正则表达式来获取 srcheight

var div = document.createElement('div');
div.innerHTML = '<img alt="" height="200" src="http://www.example.com/example.png" width="1500" style="height:200px;" />';
var elm = div.firstChild;
console.log(elm.src);
console.log(elm.height);
console.log(elm.style.height);

【讨论】:

    【解决方案2】:

    如果您选择使用正则表达式进行解析 - 最好逐步捕获信息:

    1. 首先捕获img元素

    2. 然后 - 内部元素 - 捕获 src, height, style-height 属性

    在这种情况下,您不必担心将来属性的顺序是否发生变化。代码示例:

    $str = '<img alt="" height="210" src="http://www.example.com/example1.png" width="1500" style="height:220px;" />
            <img alt="" src="http://www.example.com/example2.png" height="230" width="1500" style="height:240px;" />';
    
    preg_match_all('#<img[^>]*>#mui', $str, $images, PREG_SET_ORDER);
    
    foreach ($images as $img) {
        preg_match('#src="[^"]+"#mui', $img[0],            $m_src);
        preg_match('#height="\d+"#mui', $img[0],           $m_height);
        preg_match('#style="height:\d+px;?"#mui', $img[0], $m_st_height);
    
        var_dump('<pre>',$m_src[0], $m_height[0], $m_st_height[0], '<hr></pre>');
    }
    

    DEMO

    【讨论】:

      猜你喜欢
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 2015-09-11
      相关资源
      最近更新 更多