2011-03-24 148 views
0

我已經創建了一個函數,它將爲youtube嵌入代碼設置height,width和wmode = transparent。現在youtube正在返回iframe代碼。所以,我需要在youtube src的末尾添加「?wmode = transparent」。php preg_replace help iframe src

例如,
原始代碼:

< IFRAME標題= 「YouTube視頻播放」 WIDTH = 「420」 HEIGHT = 「349」 SRC = 「http://www.youtube.com/embed/aXNUL1-urg8」 FRAMEBORDER = 「0」 的allowFullScreen = 「」 > </IFRAME >

我希望它替換爲:

< iframe的標題= 「YouTube的視頻播放器」 WIDTH =」 mywidth 「HEIGHT =」 myheight 「SRC =」 http://www.youtube.com/embed/aXNUL1-urg8 ?WMODE =透明 「FRAMEBORDER =」 0" 的allowFullScreen = 「」 > </iframe中>

更換高度和寬度正在工作,但更換src不起作用。

我使用正則表達式如下

$圖案[] =「/src="http:\/\/www.youtube.com\/embed\/[a-zA-Z0-9._- ]「/」;
$ replacementments [] ='src =「http://www.youtube.com/embed/${1}?wmode=transparent」';

以下是我的功能。

功能SetHeightWidthVideo($標記,$ W = '200',$ H = '120') { //使其WMODE =透明

$markup = str_replace('<embed ','<embed wmode="transparent" ',$markup); 
    //$w = '200'; 
    //$h = '120'; 

    $patterns = array(); 
    $replacements = array(); 
    if(!empty($w)) 
    { 
     $patterns[] = '/width="([0-9]+)"/'; 
     $patterns[] = '/width:([0-9]+)/'; 

     $replacements[] = 'width="'.$w.'"'; 
     $replacements[] = 'width:'.$w; 
    } 

    if(!empty($h)) 
    { 
     $patterns[] = '/height="([0-9]+)"/'; 
     $patterns[] = '/height:([0-9]+)/'; 

     $replacements[] = 'height="'.$h.'"'; 
     $replacements[] = 'height:'.$h; 
    } 



    $patterns[] = '/src="http:\/\/www\.youtube\.com\/embed\/[a-zA-Z0-9._-]"/'; 
    $replacements[] = 'src="http://www.youtube.com/embed/${1}?wmode=transparent"'; 

    return preg_replace($patterns, $replacements, $markup); 

}

請幫忙。提前致謝。

+0

你需要一個'+'上的你'[A-ZA-Z0-9 ._-]結束'表達。現在它只能匹配一個字符。 – ridgerunner 2011-03-24 04:38:06

+0

ohk指出。謝謝。 :) – aayushi 2011-03-24 04:50:28

回答

2

嘗試:

$patterns[] = '/src="(.*?)"/'; 
$replacements[] = 'src="${1}?wmode=transparent"'; 

return preg_replace($patterns, $replacements, $markup); 
+0

這工作!你真棒:)謝謝。 – aayushi 2011-03-24 04:49:00

2

複製,粘貼,運行:

function setHeightWidthSrc($s, $width, $height) 
{ 
    return preg_replace(
    '@^<iframe\s*title="(.*)"\s*width="(.*)"\s*height="(.*)"\s*src="(.*?)"\s*(.*?)</iframe>[email protected]', 
    '<iframe title="\1" width="' . $width . '" height="' . $height . '" src="\4?wmode=transparent" \5</iframe>', 
    $s 
); 
} 

$original = '<iframe title="YouTube video player" 
    width="420" height="349" src="http://www.youtube.com/embed/aXNUL1-urg8" 
    frameborder="0" allowfullscreen=""></iframe> 
'; 
print "$original\n"; 
print setHeightWidthSrc($original, 100, 100) . "\n";