[英]Replace all urls as links in PHP
I want to make all the urls in a text as hyperlinks.我想将文本中的所有 url 作为超链接。 I have done the following.我做了以下事情。 But the links are missing with ':'.但是链接缺少':'。 Any help appreciated.任何帮助表示赞赏。
<?php
$string = "Hallo Studenten http://google.com/your/subpage and https://www.yahoo.com/my/subpage";
$regexp = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i";
$anchorMarkup = "<a href=\"%s://%s\" target=\"_blank\" >%s</a>";
preg_match_all($regexp, $string, $matches, \PREG_SET_ORDER);
foreach ($matches as $match) {
if (empty($match[1]) && empty($match[7])) {
$http = $match[2]?$match[2]:'http';
$replace = sprintf($anchorMarkup, $http, $match[0], $match[0], $match[1]);
$string = str_replace($match[0], $replace, $string);
}
}
echo $string;
?>
http://phpfiddle.org/lite/code/2yg5-i3uj http://phpfiddle.org/lite/code/2yg5-i3uj
It can be done with preg_replace function:可以使用preg_replace function 来完成:
$string = "Hallo Studenten http://google.com/your/subpage and https://www.yahoo.com/my/subpage";
$regexp = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i";
$anchorMarkup = "<a href=\"$0\" target=\"_blank\" >$0</a>";
echo preg_replace($regexp, $anchorMarkup, $string);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.