2013-02-06 114 views
2

Ive得到了如下功能都包裝iframe的在一個div類=「視頻容器」PHP/WordPress的的preg_match

我想要的目標僅包含一個src與SRC =「www.youtube開始的I幀

有沒有修改這個功能做更具體的辦法?在此先

感謝。

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'); 
+0

'if(!condition)continue;'在foreach中作爲第一行。使條件成爲目標條件(src以任何形式開始) – Patashu

回答

0

執行懶惰匹配(*?)和c哎呀,如果你正在尋找的字符串是在其中:

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

您也可以嘗試風格的僞選擇您喜歡的iframe或:before:after。這樣,你並不需要一個包裝元素(如:iframe[src~=youtube]:after

+0

啊,是的,我沒有想到使用僞的來包裝iframe。我給他們一個去。 – user1385827

+0

:在僞元素之前將不會工作根據我的測試和這篇文章http://stackoverflow.com/a/13056674/1385827 – user1385827

+0

上面提供的PHP youve工程。我不知道你爲什麼說在很多情況下會失敗?再次感謝你的幫助。 – user1385827

0

我想你只需要改變$pattern變量與嘗試。

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

注:作爲@alex指出,你缺少的協議,所以它應該是http://youtube.//youtube.http://www.youtube.

+0

它不應該工作,因爲缺少協議將意味着'iframe'將無法正常工作。 – alex

+0

@alex:謝謝指出,我忘了,因爲不在問題中...更新 –

+0

我不認爲你想要在角色類。如果它是可選的,請使用括號來包裝它。 – alex