PHP: STR replace by link

浪尽此生 提交于 2019-12-19 12:01:10

问题


i have this PHP chatbox.

If i would type a link in the chatbox, it would not display it as a link.

How can i use STR replace to do this?

It should respond to stuff like 'http' 'http://' '.com' '.nl' 'www' 'www.' ....

My other STR replace lines look like these:

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

Someone?


回答1:


Hey! Try this code (found at php.net somewhere):

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;
}

Uhm, broken indentation. try this http://triop.se/code.txt




回答2:


You should use regex instead. look at 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);


来源:https://stackoverflow.com/questions/1587480/php-str-replace-by-link

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!