2014-01-30 42 views
0

我已經在php中創建了一個博客。用戶可以發佈任何文字,鏈接或youtube鏈接。我使用preg_replace()來確定何時存在鏈接或youtube鏈接。這是我使用的:博客,使用鏈接或youtube鏈接職位

<?php 

//...code 


$row['comment'] = preg_replace('@(https?://([-\w.]+[-\w])+(:\d+)?(/([\w-.~:/?#\[\]\@!$&\'()*+,;=%]*)?)?)@', '<a href="$1" target="_blank">$1</a>', $row['comment']); 


$row['comment'] = preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i"," <object width=\"100px;\" height=\"100px;\"><param name=\"movie\" value=\"http://www.youtube.com/v/$1&hl=en&fs=1\"></param><param name=\"allowFullScreen\" value=\"true\"></param><embed src=\"http://www.youtube.com/v/$1&hl=en&fs=1\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"400px;\" height=\"200px;\"></embed></object>",$row['comment']); 

    // then prints the $row['comment'] 

?> 

我的preg_replace()工作正常,並確定當有鏈接或youtube鏈接成功。唯一的問題是,當發佈youtube鏈接時,它顯示2次...可能是因爲我給了$ row ['comment'] 2個不同的聲明。任何想法我怎麼能擺脫這一點?將1中的上述2個陳述合併在一起會更好嗎?我該怎麼做?或者我可以使用的任何其他「if」聲明?

任何想法如何將上述兩個語句合併爲一個?

+0

檢查一下,如果它是一個YouTube鏈接,如果它沒有檢查鏈接 – Weinz

+0

任何想法如何寫這個? – user2491321

+0

你的YouTube正則表達式應該已經「鏈接」的EXCLUDE鏈接。 –

回答

0

我更喜歡使用strpos函數來檢查一個字符串(在你的情況下url)。有關更多詳細信息,請參閱PHP.net文檔。

建議使用if結構,因爲您需要爲每種鏈接類型執行不同的實現。以下StackOverflow question是非常有用的。

+0

知道如何使用這個函數修改我的代碼? – user2491321

0

下面的代碼將做的伎倆。

function get_link_type($url) 
{ 
    if(strpos($url, 'youtube') > 0) 
    { 
     return 'youtube'; 
    } 
    else 
    { 
     return 'default'; 
    } 
} 

$url = 'http://www.google.com/watch?v=rj18UQjPpGA&feature=player_embedded'; 
$link_type = get_link_type($url); 

if($link_type == 'youtube') 
{ 
    $new_link = '<iframe width="560" height="315" src="//'. $url .'" frameborder="0" allowfullscreen></iframe>'; 
} 
else 
{ 
    $new_link = '<a href="'. $url .'">'. $url .'</a>'; 
} 

echo $new_link;