我写了一个代码,该代码将超链接添加到所有找到http://
或https://
的纯文本中。该代码非常适合https://www.google.com
和http://yahoo.com
。它将这些文本转换为具有正确地址的可单击超链接。
<?php
function convert_text_to_link($str)
{
$pattern = "/(?:(https?)://([^s<]+)|(www.[^s<]+?.[^s<]+))(?<![.,:])/i";
return preg_replace($pattern, "<a href='$0' target='_blank'>$0</a>", $str);
}
$str = "https://www.google.com is the biggest search engine. It's competitors are http://yahoo.com and www.bing.com.";
echo convert_text_to_link($str);
?>
但是当我的代码看到www.bing.com
时,虽然它添加了超链接,但href
属性也变得www.bing.com
。没有http://
预先添加它。因此,如果没有链接,链接将变得不可用http://localhost/myproject/www.bing.com
将无处可去。
如何将http://
添加到www.bing.com
中,以便它应该变得http://www.bing.com
?
这是你的函数。试试这个。
function convert_text_to_link($str) {
$pattern = '@(http)?(s)?(://)?(([a-zA-Z])([-w]+.)+([^s.]+[^s]*)+[^,.s])@';
return preg_replace($pattern, '<a href="http$2://$4" target="_blank">$0</a>', $str);
}
您应该尝试检查这是否有效:
window.location = window.location.href.replace(/^www./, 'https:');
也许你会得到你的解决方案。
我也刚刚了解了一些其他方法,您可以根据您的代码和要求尝试它们:
1.
str_replace("www.","http://","$str");
此处的测试区分大小写。这意味着,如果字符串最初是,这会将其更改为 http://Http://example.com 这可能不是您想要的。
- 尝试正则表达式:
if (!$str.match(/^[a-zA-Z]+:///))
{
$str = 'http://' + $str;
}
.
希望这有帮助。