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

58,408

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>";
Share:
58,408
EmmyS
Author by

EmmyS

SOreadytohelp

Updated on January 25, 2020

Comments

  • EmmyS
    EmmyS over 4 years

    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.

    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.