如何将文本 URL 转换为 PHP 页面中的可点击链接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4687662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:58:55  来源:igfitidea点击:

How can I convert a text URL into a clickable link in a PHP page?

phpregexurl

提问by EmmyS

I'm sure this is a really simple, obvious answer, but my brain is fried and I just can't seem to get it. I have a PHP site that allows users to post information to a text field in mySQL. The posts can all be viewed online. The field is a textarea in the HTML form when in post/edit mode, and static text in read mode. The users want to be able to include a URL in their posts and have it display as a clickable link, without having to include HTML in the field (which I don't want them to be able to do anyway - too risky.) So this is something that needs to be done when the data is displayed, rather than inserting html into the text when it's saved to the database.

我确信这是一个非常简单、显而易见的答案,但我的大脑被炸了,我似乎无法理解。我有一个 PHP 站点,允许用户将信息发布到 mySQL 中的文本字段。这些帖子都可以在线查看。该字段在发布/编辑模式下是 HTML 表单中的文本区域,在阅读模式下是静态文本。用户希望能够在他们的帖子中包含一个 URL 并将其显示为可点击的链接,而不必在字段中包含 HTML(我不希望他们无论如何都能这样做 - 太冒险了。)所以这是在显示数据时需要做的事情,而不是在文本保存到数据库时将 html 插入到文本中。

The code for the display is pretty simple:

显示代码非常简单:

$query = "SELECT * FROM meetings where id=".$_GET['id'];
$result = mysqli_query($dbc, $query) or die('Error querying database');
$rows = mysqli_fetch_array($result);

echo "<p><div id=\"articleBody\">". $rows['body']. "</div></p>";

Is there a function I can put around $rows['body'] that would display anything starting with http as a clickable link? Keeping in mind that the variable may or may not actually contain a URL.

有没有我可以在 $rows['body'] 周围放置的函数,它将以 http 开头的任何内容显示为可点击的链接?请记住,变量实际上可能包含也可能不包含 URL。

回答by Michael Irigoyen

Use preg_replaceto accomplish this:

使用preg_replace来实现:

$html = preg_replace('"\b(http://\S+)"', '<a href=""></a>', $rows['body'])
echo "<p><div id=\"articleBody\">".$html."</div></p>";

回答by Ben

$out = $rows['body'];

echo "<p><div id='articleBody'>";

if(substr($out,0,4)=='http') { echo "<a href='#'>".$out."</a>"; }
else { echo $out; } 

echo "</div></p>";