PHP:STR替换为链接

时间:2009-10-19 08:14:38

标签: php text hyperlink

我有这个PHP聊天框。

如果我在聊天框中输入一个链接,它就不会将其显示为链接。

我如何使用STR替换来执行此操作?

它应该响应'http''http://''。com''。nl''www''www'。 ....

我的其他STR替换行如下所示:

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

有人?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

你应该使用正则表达式。看看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);