Span regex replacement
I have a text in my databse. For example:
Dummy Text Here...
<span class="youtube">nmkW544sK9U</span>
Dummy Text Here...
<span class="youtube">yUBKZvq5G2g</span>
...and I need it to be replaced with:
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.yo开发者_开发百科utube.com/embed/yUBKZvq5G2g?rel=0"></iframe>
But I don't know regular expressions well enough and ask you to help me.
As a general rule, don't use regex to parse HTML. It will cause you pain.
The nicest way to do this is with a genuine DOM parser. PHP's DOMDocument
is ideal.
For instance:
$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();
Something along these lines should work.
$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);
精彩评论