2013-10-14 64 views
0

我不確定是否以正確的方式進行此操作。我想採取一個簡單的鏈接,像這樣;使用str_replace將鏈接格式化爲嵌入式超鏈接的圖像

https://www.youtube.com/watch?v=examplevideo

,並把它變成

<a href= 'https://www.youtube.com/embed/examplevideo' target=_blank><img src='http://img.youtube.com/vi/examplevideo/0.jpg' width='536' border='1'></a>

在過去,我已經能夠通過使用str_replace函數,這是非常簡單的更改鏈接,因爲你會拉出一個模式然後用另一個替換它。但是,在這種情況下,輸出中保留的模式會顯示兩次。 str_replace是否是正確的方法?

回答

1

這裏有一個簡單的方法來做到這一點...

// $video_url = "https://www.youtube.com/watch?v=examplevideo"; 
$videoId = str_replace("https://www.youtube.com/watch?v=", "", $video_url); 
enter code here 
$videoLink = "<a href= 'https://www.youtube.com/embed/$videoId' target=_blank><img src='http://img.youtube.com/vi/$videoId/0.jpg' width='536' border='1'></a>" 

當然,如果您的網址是更復雜(如?V = ABC & T = 123),那麼這將無法正常工作,而你將不得不解析URL更像URL(即不使用str_replace)。

+0

有趣的是,你用str_replace剩下的東西創建了一個變量,然後你將它應用到一個新的變量。謝謝,Hamza。 – Kimomaru

+0

@Kimomaru:看到我的答案在下面。 –

1

您可以使用parse_url()parse_str()獲取視頻ID,然後使用sprintf()構建嵌入代碼。

我做了一個小功能:

function getEmbedded($url) { 
    $parts = parse_url($url); 
    $parsed = parse_str($parts['query'], $params); 
    $result = sprintf("<a href= 'https://www.youtube.com/embed/%s' 
     target=_blank><img src='http://img.youtube.com/vi/%s/0.jpg' 
     width='536' border='1'></a>", $params['v'],$params['v']); 
    return $result; 
} 

用法:

echo getEmbedded($url); 

這比使用str_replace()更高效,即使有視頻網址附加查詢參數的工作原理。