php - 正则表达式/DOM 解析用缩略图替换 YouTube iframe,同时保留字符串

标签 php regex dom

我不知道最好使用 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/ )

最佳答案

我将使用 DOMXPath 来实现:

$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/

相关文章:

javascript - 简化代码

java - 修改Java中现有的XML样式表处理指令

php - 在mysql表上使用for循环

php - smarty 模板 - 在 url 中传递 javascript 变量

Python 的正则表达式模块 : repeating 'backreferences' does not appear to work correctly

jQuery:使用正则表达式匹配货币

javascript - <img> 图像的 HTML Javascript getElementById 返回 null

php - Mongodb 不使用 php 获取嵌入式文档

javascript - 单击时可下载文件的超链接,并为每次下载增加一个字段

java - 获取除 to_date 模式之外的绑定(bind)名称