2012-08-01 50 views
3

我有如下文字如何在文本中替換YouTube網址?

"I made this video on my birthday. All of my friends are here in party. Click play to video the video 
http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit " 

我想是更換該上述網址可

"I made this video on my birthday. All of my friends are here in party. Click play to video the video 

     <iframe width="853" height="480" src="http://www.youtube.com/embed/G3j6avmJU48" frameborder="0" allowfullscreen></iframe> " 

我知道我們可以從上面的URL獲得YouTube視頻ID在下面的腳本

 preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $word, $matches); 


     $youtube_id = $matches[0]; 

但我不知道如何替換url

http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit 

<iframe width="853" height="480" src="http://www.youtube.com/embed/G3j6avmJU48" frameborder="0" allowfullscreen></iframe> 

請幫助謝謝

+2

這是一個[複製](http://stackoverflow.com/questions/1188129/replace-urls-in -text-with-html-links) – Matt 2012-08-01 21:20:42

+0

當它必須從url獲取id並用iframe標記替換url時它是如何複製的?所描述的鏈接只是一個正常的鏈接。 – user1494854 2012-08-01 21:29:19

回答

1

使用的preg_replace函數(see PHP preg_replace() Documentation

編輯:

使用的preg_replace如下:您使用括號()來包裝什麼你想要在正則表達式中捕獲(第一個參數),然後在s中使用$ n(n正則表達式中的圓括號)第二個參數來獲取您捕獲的內容。

在你的情況,你應該有這樣的事情:

$text = "I made this video on my birthday. All of my friends are here in party. Click play to video the video http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit"; 

$replaced = preg_replace('#http://www\.youtube\.com/watch\?v=(\w+)[^\s]+#i','<iframe width="853" height="480" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>',$text); 

對於更高級的用法和示例見我之前,只要你的文檔鏈接。

希望這可以幫助你更多。

編輯2: 正則表達式是錯誤的,我修好了。

+0

如果我知道如何使用preg_place它不會要求幫助。 :)謝謝 – user1494854 2012-08-01 21:30:06

+0

感謝它的工作完美:) – user1494854 2012-08-01 23:04:28

+0

不客氣:) 很高興它幫助你 – Oussama 2012-08-01 23:25:58

0

您可以使用此示例代碼來實現它的基礎上,@馬特評論:

<?php 
$text = "I made this video on my birthday. All of my friends are here in party. Click play to video the video 
http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit "; 

$rexProtocol = '(https?://)?'; 
$rexDomain = '(www\.youtube\.com)'; 
$rexPort  = '(:[0-9]{1,5})?'; 
$rexPath  = '(/[!$-/0-9:;[email protected]_\':;!a-zA-Z\x7f-\xff]*?)?'; 
$rexQuery = '(\?[!$-/0-9:;[email protected]_\':;!a-zA-Z\x7f-\xff]+?)?'; 
$rexFragment = '(#[!$-/0-9:;[email protected]_\':;!a-zA-Z\x7f-\xff]+?)?'; 

function callback($match) 
{ 
    $completeUrl = $match[1] ? $match[0] : "http://{$match[0]}"; 
    $videoId = array(); 
    preg_match ("|\?v=([a-zA-Z0-9]*)|", $match[5], $videoId); 

    return '<iframe src="http://www.youtube.com/embed/' . $videoId[1] . '" width="853" height="480"></iframe>'; 
} 
print preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&", 'callback', htmlspecialchars($text)); 

?>