我的数据库中有一个文本。例如:
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>
但我不太了解正则表达并请你帮助我。
答案 0 :(得分: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();
答案 1 :(得分:0)
这些方面应该有所作为。
$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);