开发者

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. 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开发者_Python百科 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.

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.


Use preg_replace to accomplish this:

$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>";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜