2009-10-19 27 views
0

我有這個PHP聊天室。PHP:STR取代鏈接

如果我要在聊天框中鍵入鏈接,它不會將其顯示爲鏈接。

如何使用STR替換來做到這一點?

它應該對'http''http://''.com''.nl''www''www。' ....

我的其他STR代替線條看起來像這樣:

$bericht = str_replace ("STRING1","STRINGREPLACEMENT1",$bericht); 

人嗎?

回答

1

嘿!試試這個代碼(在php.net找到的地方):

function format_urldetect($text) 
{ 

    $tag = " rel=\"nofollow\""; 
    // 
    // First, look for strings beginning with http:// that AREN't preceded by an <a href tag 
    // 
    $text = preg_replace("/(?<!<a href=(\"|'))((http|ftp|http)+(s)?:\/\/[^<>\s]+[\w])/i", "<a target=\"_new\" class=\"httplink\" href=\"\\0\"" . $tag . ">\\0</a>", $text); 
    // 
    // Second, look for strings with casual urls (www.something.com...) and make sure they don't have a href tag OR a http:// in front, 
    // since that would have been caught in the previous step. 
    // 
    $text = preg_replace("/(?<!<a href=(\"|')http:\/\/)(?<!http:\/\/)((www)\.[^<>\s]+[\w])/i", "<a target=\"_new\" class=\"httplink\" href=\"http://\\0\"" . $tag . ">\\0</a>", $te 
xt); 
    $text = preg_replace("/(?<!<a href=(\"|')https:\/\/)(?<!http:\/\/)((www)\.[^<>\s]+[\w])/i", "<a target=\"_new\" class=\"httplink\" href=\"http://\\0\"" . $tag . ">\\0</a>", $t 
ext); 
    return $text; 
} 

呃,破損的壓痕。試試這個http://triop.se/code.txt

+0

謝謝,這讓我在路上。 – 2009-10-22 09:14:57

+0

試過了,工作!謝謝。 – 2009-11-06 07:15:04

0

你應該改用regex。看看preg_replace

$regex = '`(\s|\A)(http|https|ftp|ftps)://(.*?)(\s|\n|[,.?!](\s|\n)|$)`ism'; 
$replace = '$1<a href="$2://$3" target="_blank">$2://$3</a>$4' 

$buffer = preg_replace($regex,$replace,$buffer);