简体   繁体   English

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

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

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. 我有一个PHP站点,允许用户将信息发布到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. 在发布/编辑模式下,该字段是HTML表单中的textarea,在读取模式下是静态文本。 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. 用户希望能够在他们的帖子中包含一个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? 是否有一个函数我可以放在$ rows ['body']周围,它会显示任何以http开头的可点击链接? Keeping in mind that the variable may or may not actually contain a URL. 请记住,变量实际上可能包含或不包含URL。

Use preg_replace to accomplish this: 使用preg_replace来完成此任务:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM