【问题标题】:Span regex replacement跨度正则表达式替换
【发布时间】:2011-06-05 21:37:15
【问题描述】:

我的数据库中有一个文本。例如:

Dummy Text Here...
<span class="youtube">nmkW544sK9U</span>

Dummy Text Here...
<span class="youtube">yUBKZvq5G2g</span>

...我需要将其替换为:

Dummy Text Here...
<iframe width="640" height="395" frameborder="0" allowfullscreen="" src="http://www.youtube.com/embed/nmkW544sK9U?rel=0"></iframe>

Dummy Text Here...
<iframe width="640" height="395" frameborder="0" allowfullscreen="" src="http://www.youtube.com/embed/yUBKZvq5G2g?rel=0"></iframe> 

但是我对正则表达式不够了解,请您帮助我。

【问题讨论】:

    标签: php regex youtube preg-replace


    【解决方案1】:

    一般来说,不要使用正则表达式来解析 HTML。它会让你感到痛苦。

    最好的方法是使用真正的 DOM 解析器。 PHP 的DOMDocument 非常理想。

    例如:

    $dom = new DOMDocument;
    $dom->loadHTML($yourHTML);
    
    $xpath = new DOMXPath($dom);
    
    $nodes = $xpath->query('//span[@class="youtube"]');
    
    while ($node = $nodes->item(0)) {
        $iframe = $dom->createElement('iframe');
        $iframe->setAttribute('width', 640);
        $iframe->setAttribute('height', 395);
        $iframe->setAttribute('frameborder', 0);
        $iframe->setAttribute('allowfullscreen', '');
        $iframe->setAttribute('src', 'http://www.youtube.com/embed/' . $node->nodeValue . '?rel=0');
    
        $node->parentNode->replaceChild($iframe, $node);
    }
    
    $yourHTML = $dom->saveHTML();
    

    【讨论】:

    • 也许你能解释一下为什么正则表达式如此痛苦?对于更复杂的操作我同意你,但是对于这么简单的替换我看不出有什么问题?
    • @Arend 可能没问题。直到源改变。或者它会变得稍微复杂一些。如果模式是绝对确定的,那可能没问题——但如果它稍微改变一下,你就完蛋了。
    • @Arend 正则表达式无法轻松处理标签的嵌套。除非您确定静态标签嵌套,否则这就是问题所在。
    • @millebii,当然,当然。但这不是一个明确的例子,说明您需要对嵌套提供高端支持。说清楚,我同意你的看法。但我之所以问这些问题,是因为我发现“它会导致你痛苦”之类的言论毫无帮助。
    • @Arend 这句话的意思很幽默,但它包含真理。使用正则表达式解析 HTML 通常不会以一种有吸引力且稳定的方式解决您的问题,因为它太不灵活了。
    【解决方案2】:

    按照这些思路应该可以工作。

    $replacement = '<iframe width="640" height="395" frameborder="0" allowfullscreen="" src="http://www.youtube.com/embed/$1?rel=0"></iframe>';
    preg_replace('/<span class="youtube">(\w+)<\/span>/', $replacement, $string);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 2016-12-12
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多