我不知道最好使用 DOM 解析器还是正则表达式,但我想用缩略图替换我的博文中的所有 YouTube iframe。我确实找到了返回所有拇指的方法,但不是在字符串中返回的。我想保持字符串不变,但用缩略图替换 Iframe。
此代码返回所有 YouTube 视频:
$data = get_the_content();
// Find all unique YouTube videos
$re_youtube = '%youtube\.com/(?:v/|watch\?v=|embed/)(\w{10,12})\b%';
$count = preg_match_all($re_youtube, $data, $matches);
for ($i = 0; $i < $count; ++$i) {
$videos[$matches[1][$i]] = 'yt';
}
foreach ( $videos as $video => $v) {
if ( $v == 'yt' ) {
echo '<div id="yt_'.$video.'" class="viddid viddid_thumb" onclick="myFunction(\''.$video.'\')"><img src="http://img.youtube.com/vi/'.$video.'/0.jpg"></div>';
}
}
我确信我可以使用 preg_replace 来实现我正在寻找的东西?我非常高兴能得到任何帮助!
我一直在进行一些圆顶解析来清理 HTML 中的段落。它看起来像这样:
// Set the right encoding of string
$content = mb_convert_encoding($content, 'html-entities', 'utf-8');
$DOM = new DOMDocument('1.0', 'UTF-8');
$DOM->substituteEntities = TRUE;
$DOM->loadHTML($content);
foreach($DOM->getElementsByTagName("iframe") as $iframe)
{
foreach($p->attributes as $attr)
$p->parentNode->removeChild($p);
}
$content = $DOM->saveHTML();
所以现在我需要一些帮助来将两者结合起来。
(以下是该页面的示例: http://2famous.tv/2013/11/17/middle-eastern-artists-donate-more-than-1-1-million-of-art-to-help-syrian-refugee-children/ )
最佳答案
我将使用 DOM
和 XPath
来实现:
$doc = new DOMDocument();
$doc->loadHTML($your_html_string);
$selector = new DOMXPath($doc);
// use the starts-with function to select iframes of interest
foreach($selector->query('//iframe[starts-with(@src, "//www.youtube.com")]')
as $iframe
) {
$iframe->parentNode->removeChild($iframe);
}
echo $doc->saveHTML();
关于php - 正则表达式/DOM 解析用缩略图替换 YouTube iframe,同时保留字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20571044/