2

我有以下函数将所有 iframe 包装在 div class="video-container" 中

我只想定位包含以 src="www.youtube 开头的 src 的 iframe

有没有办法把这个功能修改得更具体一些?

提前致谢。

function div_wrapper($content) {
// match any iframes
$pattern = '~<iframe.*</iframe>~';
preg_match_all($pattern, $content, $matches);

foreach ($matches[0] as $match) {
    // wrap matched iframe with div
    $wrappedframe = '<div class="video-container">' . $match . '</div>';

    //replace original iframe with new in content
    $content = str_replace($match, $wrappedframe, $content);
}

return $content;    
}
add_filter('the_content', 'div_wrapper');
4

2 回答 2

0

执行惰性匹配 ( *?),并检查您要查找的字符串是否存在于其中:

// match any iframes
$pattern = '~<iframe.*?</iframe>~';
$content = preg_replace_callback($pattern, function($matches){

  if(strpos($matches[0], 'youtube') !== false) 
    return '<div class="video-container">' . $matches[0] . '</div>';

  return $matches[0];

}, $content);

不用说,这在很多情况下都会失败。如果您想要一些可靠的东西,请使用 XML 解析器(请参阅DomDocument::getElementsByTagNameDomElement::getAttribute.

您还可以尝试使用伪选择器(如:before或)来设置 iframe 的样式:after。这样你就不需要包装元素(例如。iframe[src~=youtube]:after

于 2013-02-06T06:13:59.357 回答
0

我认为您只需要更改$pattern变量即可。尝试:

$pattern = '~<iframe.*src*=\'.*(http\:?)*\/\/*(www\.?)*youtube\..*</iframe>~';

注意:正如@a​​lex 指出的那样,您缺少协议,因此应该是http://youtube.,//youtube.http://www.youtube.

于 2013-02-06T06:20:19.937 回答