可能重复:
How do I auto convert an url into a hyper link in PHP?
让我们说,我的网站上有一个文本字段,用户可以输入他想要的任何内容。 如果用户输入了网址,我想在后台为此网址添加代码。因此我需要逻辑来识别网址。
实施例 用户输入文本:
Please visit me at my website: http://www.mywebsite.org
我想将后台的代码更改为:
Please visit me at my website: <a href="http://www.companywebsite.com/redirect.php?http://www.mywebsite.org">http://www.mywebsite.org</a>
如何在提交文本后更改该链接?
答案 0 :(得分:2)
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text);
} else {
// if no urls in the text just return the text
echo $text;
}
?>
答案 1 :(得分:0)
是肯定的。只需使用正则表达式。见preg_replace
答案 2 :(得分:0)
如果您正在保存用户输入并在网站上显示(正如我猜的那样),您应该保存原始输入并在渲染时应用逻辑。
请参阅此处了解逻辑: Detect URL and add achor-tags around it
$link = preg_replace("/(http:\/\/[^\s]+)/", "<a href=\"$1\">$1</a>", $link);
答案 3 :(得分:0)
哟也可以试试
$text = "Please visit me at my website: http://www.mywebsite.org
Please visit me at my website: http://www.mywebsite.org";
$newText = preg_replace('/((http|https|ftp):\/\/[^\s]+)/i',
'<a href="$1" class="link1" target="_blank">$1</a>', $text);
echo $newText;
这一个