2013-09-22 37 views
0

我想知道如何將字符串模式更改爲其他內容。我正在建立一個小論壇,並希望在有人將鏈接輸入到論壇的textarea部分時嵌入youtube視頻。 Youtube的視頻鏈接是這樣的;php中的字符串修改

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

但是,我想改變這個字符串看起來像這樣;

<iframe width="420" height="315" 
src="https://www.youtube.com/embed/examplevideo"> 
</iframe> 

所以,我會換掉除了「examplevideo」字符串以外的所有東西。由於這個鏈接將被包含在表單textarea部分的其他文本中,我的猜測是我將不得不建立一個if語句來查找任何說「https://www.youtube.com/watch?v=」的東西我會使用字符串比較嗎?這將如何工作?

+1

你不能使用:[str_replace](http://php.net/manual/en/function.str-replace.php)? –

+0

你不只是替換,你也在附加html。 – Kimomaru

回答

3

假設你想呼應的結果:

if(strpos($url,"youtube.com/watch?v=")){ 
    echo '<iframe width="420" height="315" src="'; 
    echo str_replace('/watch?v=','/embed/',$url); 
    echo '"></iframe>'; 
}else{ 
    echo $url; 
} 

strpos手冊:http://php.net/manual/en/function.strpos.php
str_replace手冊:http://php.net/manual/en/function.str-replace.php

+0

謝謝你,穆斯曼!很有幫助。 – Kimomaru

+0

@Kimomaru我增加了'str_replace'來代替使用嵌入網址。 – Mooseman

2

簡單的正則表達式的解決方案得到一切後?v=

$video_name = preg_replace('/^.*\?v=/', '', 'https://www.youtube.com/watch?v=examplevideo'); 
1

我會建議使用Regu LAR表達式:

// $url is 'https://www.youtube.com/embed/examplevideo' 
$url = preg_replace('/https?\:\/\/www.youtube.com/watch\?v=(.*)/i', 'https://www.youtube.com/embed/$1', $url); 

這樣做是什麼,它會尋找一個字符串以「http://www.youtube.com/watch?v=」(我加的,這樣它匹配HTTP和HTTPS「?」),採取一切遵循並追加這' https://www.youtube.com/embed/'。