2009-09-09 98 views
0

我已經編寫了一個PHP函數來獲取具有寬度和高度的視頻嵌入代碼,並允許您指定新的寬度。該功能將使用適當的縮放因子縮小高度。我發現寬度和高度並不總是相鄰的,所以我做了一些我沒有預感的呼叫是不必要的。有沒有更好的方法來清理以下內容?在PHP中優化正則表達式替換

function scale_video($video_embed,$new_width = 200){ 

    preg_match('/width="(\d)*"/', $video_embed, $width); 
    preg_match('/height="(\d)*"/', $video_embed, $height); 
    $width = substr($width[0],7,-1); 
    $height = substr($height[0],8,-1); 

    $scale_factor = $new_width/$width; 
    $new_height = floor($height * $scale_factor); 

    $video_embed = preg_replace('/width="(\d)*"/','width="'.$new_width.'"',$video_embed); 
    $video_embed = preg_replace('/height="(\d)*"/','height="'.$new_height.'"',$video_embed); 

    return $video_embed; 
} 

回答

4

我想提醒的唯一事情是你的正則表達式模式有待提高

/width="(\d)*"/ 

應該是:

/width="(\d*)"/ 

這會給你一個你正在尋找的整個值的組,而不是模式中每個字符的組。這樣,那麼你可以改變:

$width = substr($width[0],7,-1); 

$width = $width[1]; 

您可以輕鬆地應用此高度爲好。通過將前兩個參數放入數組,可以將您的結束替換轉換爲一個調用。

綜上所述,筆者建議如下:

function scale_video($video_embed,$new_width = 200){ 

    // only process if both matches have results 
    if(preg_match('/width="(\d+)"/', $video_embed, $width) && 
     preg_match('/height="(\d+)"/', $video_embed, $height) { 

     $width = $width[1]; 
     $height = $height[1]; 

     $scale_factor = $new_width/$width; 
     $new_height = floor($height * $scale_factor); 

     $video_embed = preg_replace(array('/width="(\d+)"/', '/height="(\d+)"/'), array('width="'.$new_width.'"', 'height="'.$new_height.'"'), $video_embed); 

    } 

    return $video_embed; 
} 
0

一個更好的辦法可能是使用preg_replace_callback()/e modifier(爲「ê計價碼)來設置的東西,讓你只做每個模式的一個正則表達式匹配,是這樣的:

$video_embed = preg_replace_callback('/width="(\d)*"/', 'scale_video_width_callback', $video_embed); 

function scale_video_width_callback($match) { 
    // transform match and return transformed value 
}