在PHP中将纯文本URL转换为HTML超链接

我有一个简单的评论系统,人们可以在纯文本字段中提交超链接。 当我将这些logging从数据库显示回网页时,我可以使用哪些RegExp将这些链接转换为HTMLtypes的锚链接?

我不希望algorithm与任何其他types的链接,只是HTTP和HTTPS。

这是另一个解决scheme,这将捕获所有http / https / www并转换为可点击的链接。

$url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i'; $string = preg_replace($url, '<a href="$0" target="_blank" title="$0">$0</a>', $string); echo $string; 

或者只是抓住http / https,然后使用下面的代码。

 $url = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/'; $string= preg_replace($url, '<a href="$0" target="_blank" title="$0">$0</a>', $string); echo $string; 

编辑:下面的脚本将捕获所有的urltypes,并将其转换为可点击的链接。

 $url = '@(http)?(s)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@'; $string = preg_replace($url, '<a href="http$2://$4" target="_blank" title="$0">$0</a>', $string); echo $string; 

新的更新,如果你有string(S),然后使用下面的代码块,感谢@AndrewEllis指出这一点。

 $url = '@(http(s)?)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@'; $string = preg_replace($url, '<a href="http$2://$4" target="_blank" title="$0">$0</a>', $string); echo $string; 

那么,沃洛米克的答案就更接近了。 为了进一步推进,我在这里做了什么来忽视超链接结尾的尾随时期 。 我也考虑过URI片段。

 public static function makeClickableLinks($s) { return preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $s); } 
 <? function makeClickableLinks($text) { $text = html_entity_decode($text); $text = " ".$text; $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '<a href="\\1" target=_blank>\\1</a>', $text); $text = eregi_replace('(((f|ht){1}tps://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '<a href="\\1" target=_blank>\\1</a>', $text); $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1<a href="http://\\2" target=_blank>\\2</a>', $text); $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[az]{2,3})', '<a href="mailto:\\1" target=_blank>\\1</a>', $text); return $text; } // Example Usage echo makeClickableLinks("This is a test clickable link: http://www.websewak.com You can also try using an email address like test@websewak.com"); ?> 

请参阅http://zenverse.net/php-function-to-auto-convert-url-into-hyperlink/ 。 这是wordpress解决它的方式

 function _make_url_clickable_cb($matches) { $ret = ''; $url = $matches[2]; if ( empty($url) ) return $matches[0]; // removed trailing [.,;:] from URL if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) { $ret = substr($url, -1); $url = substr($url, 0, strlen($url)-1); } return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $ret; } function _make_web_ftp_clickable_cb($matches) { $ret = ''; $dest = $matches[2]; $dest = 'http://' . $dest; if ( empty($dest) ) return $matches[0]; // removed trailing [,;:] from URL if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) { $ret = substr($dest, -1); $dest = substr($dest, 0, strlen($dest)-1); } return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret; } function _make_email_clickable_cb($matches) { $email = $matches[2] . '@' . $matches[3]; return $matches[1] . "<a href=\"mailto:$email\">$email</a>"; } function make_clickable($ret) { $ret = ' ' . $ret; // in testing, using arrays here was found to be faster $ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret); $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret); $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret); // this one is not in an array because we need it to run last, for cleanup of accidental links within links $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret); $ret = trim($ret); return $ret; } 

评分最高的答案没有为我做这个工作,下面的链接没有被正确的replace:

http://www.fifa.com/worldcup/matches/round255951/match=300186487/index.html#nosticky

经过一些谷歌search和一些testing,这就是我想出的:

 public static function replaceLinks($s) { return preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-=#]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $s); } 

我不是正则expression式的专家,实际上它让我困惑:)

所以请随时评论和改进这个解决scheme。

 public static function makeClickableLinks($s) { return preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.-]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $s); } 

我build议不要像这样在飞行中做很多事情。 我更喜欢使用简单的编辑器界面,如在stackoverflow中使用。 它被称为Markdown 。

MkVal的答案是可行的,但是如果我们已经有了锚点链接的话,它会以怪异的格式呈现文本。

在这两种情况下,这个解决scheme适用于我:

 $s = preg_replace ( "/(?<!a href=\")(?<!src=\")((http|ftp)+(s)?:\/\/[^<>\s]+)/i", "<a href=\"\\0\" target=\"blank\">\\0</a>", $s ); 

我使用的是一个源自question2answer的函数,它接受html中的纯文本和纯文本链接:

 // $html holds the string $htmlunlinkeds = array_reverse(preg_split('|<[Aa]\s+[^>]+>.*</[Aa]\s*>|', $html, -1, PREG_SPLIT_OFFSET_CAPTURE)); // start from end so we substitute correctly foreach ($htmlunlinkeds as $htmlunlinked) { // and that we don't detect links inside HTML, eg <img src="http://..."> $thishtmluntaggeds = array_reverse(preg_split('/<[^>]*>/', $htmlunlinked[0], -1, PREG_SPLIT_OFFSET_CAPTURE)); // again, start from end foreach ($thishtmluntaggeds as $thishtmluntagged) { $innerhtml = $thishtmluntagged[0]; if(is_numeric(strpos($innerhtml, '://'))) { // quick test first $newhtml = qa_html_convert_urls($innerhtml, qa_opt('links_in_new_window')); $html = substr_replace($html, $newhtml, $htmlunlinked[1]+$thishtmluntagged[1], strlen($innerhtml)); } } } echo $html; function qa_html_convert_urls($html, $newwindow = false) /* Return $html with any URLs converted into links (with nofollow and in a new window if $newwindow). Closing parentheses/brackets are removed from the link if they don't have a matching opening one. This avoids creating incorrect URLs from (http://www.question2answer.org) but allow URLs such as http://www.wikipedia.org/Computers_(Software) */ { $uc = 'az\x{00a1}-\x{ffff}'; $url_regex = '#\b((?:https?|ftp)://(?:[0-9'.$uc.'][0-9'.$uc.'-]*\.)+['.$uc.']{2,}(?::\d{2,5})?(?:/(?:[^\s<>]*[^\s<>\.])?)?)#iu'; // get matches and their positions if (preg_match_all($url_regex, $html, $matches, PREG_OFFSET_CAPTURE)) { $brackets = array( ')' => '(', '}' => '{', ']' => '[', ); // loop backwards so we substitute correctly for ($i = count($matches[1])-1; $i >= 0; $i--) { $match = $matches[1][$i]; $text_url = $match[0]; $removed = ''; $lastch = substr($text_url, -1); // exclude bracket from link if no matching bracket while (array_key_exists($lastch, $brackets)) { $open_char = $brackets[$lastch]; $num_open = substr_count($text_url, $open_char); $num_close = substr_count($text_url, $lastch); if ($num_close == $num_open + 1) { $text_url = substr($text_url, 0, -1); $removed = $lastch . $removed; $lastch = substr($text_url, -1); } else break; } $target = $newwindow ? ' target="_blank"' : ''; $replace = '<a href="' . $text_url . '" rel="nofollow"' . $target . '>' . $text_url . '</a>' . $removed; $html = substr_replace($html, $replace, $match[1], strlen($match[0])); } } return $html; } 

由于接受括号和其他字符的链接,有点多的代码,但可能有帮助。

试试这个:

 $s = preg_replace('/(?<!href="|">)(?<!src=\")((http|ftp)+(s)?:\/\/[^<>\s]+)/is', '<a href="\\1" target="_blank">\\1</a>', $s); 

它跳过现有的链接(如果我们已经有一个href,它不会在href里面添加一个href)。 否则,它会添加一个空白目标的href。

如果是的话,你想做的是把普通的文本转换成http链接。 以下是我认为可以提供的帮助:

 <?php $list = mysqli_query($con,"SELECT * FROM list WHERE name = 'table content'"); while($row2 = mysqli_fetch_array($list)) { echo "<a target='_blank' href='http://www." . $row2['content']. "'>" . $row2['content']. "</a>"; } ?>