如何仅从数据中获取URL

时间:2013-07-13 17:59:49

标签: php html tags variables

我有一个小问题,我需要帮助。

假设$ post ['text']等于以下数据:“https://stackoverflow.com/blah?blah是一个非常酷的网站”,怎么可能只在类型标记中创建URL位... < / p>

所以最终的HTML结果会像

那样
<p><a href="https://stackoverflow.com/blah?blah">https://stackoverflow.com/blah?blah</a> is such a cool website</p>

我有点像菜鸟。我实际上是一个14岁的孩子,仍然有点新的代码,但我喜欢它!

2 个答案:

答案 0 :(得分:3)

您可以使用正则表达式。

function make_hyperlink($text)
{
    // match protocol://address/path/
    $text = preg_replace("{[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*}", "<a href=\"\\0\" target='_blank'>\\0</a>", $text);

    // match www.something
    $text = preg_replace("{(^| )(www([.]?[a-zA-Z0-9_/-])*)}", "\\1<a href=\"http://\\2\" target='_blank'>\\2</a>", $text);

    // return $text
    return $text;
}

echo make_hyperlink('http://stackoverflow.com/blah?blah');

使用上述功能。它将从简单的URL文本替换URL。

答案 1 :(得分:1)

   <p> <a href="<?=$_POST['text']?>"> <?=$_POST['text']?> </a> is a cool website </p>