0

People go online and submit an article, with a title and description. And people often include links but they appear as basic text. I want a way in which when people include a url, it is recognized as a working link. I have written a code, but it only scans one row and doesn't seem to work in the actual table, as it is echoed outside of the table.

Basically...i want a table where when a link is submitted, a hyperlink is made. Any ideas? This updated code below keeps the same thing going on.

My code is below:

      $query = "SELECT * FROM rumours ORDER BY id DESC";
     $query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
    while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$band = $row['band'];
$title = $row['Title'];
$description = $row['description'];

$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

// The Text you want to filter for urls
 // Check if there is a url in the text
  if(preg_match($reg_exUrl, $description, $url)) {
   // make the urls hyper links
   preg_replace($reg_exUrl, '<a href="'.$url[0].'">'.$url[0].'</a>', $description);

      }

   echo "<table border='1'>";
   echo "<tr>";
   echo "<td> $title  </td>";
   echo "</tr>";
   echo "<tr>";
   echo "<td class = 'td1'> $description </td>";
   echo "</tr>";
   echo "</table>";

}
James Sables
  • 1
  • 1
  • 2
  • See this question: http://stackoverflow.com/questions/1188129/replace-urls-in-text-with-html-links – Ollie Oct 12 '12 at 18:12

2 Answers2

0

It's because you print out before you do the replace with preg_replace...

Put your preg inside your loop like that :

$query = "SELECT * FROM rumours ORDER BY id DESC";
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
while ($row = mysql_fetch_assoc($query)) {
    $id = $row['id'];
    $band = $row['band'];
    $title = $row['Title'];
    $description = $row['description'];

    $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

    // The Text you want to filter for urls

    // Check if there is a url in the text
    if(preg_match($reg_exUrl, $description, $url)) {
           // make the urls hyper links
           preg_replace($reg_exUrl, '<a href="'.$url[0].'">'.$url[0].'</a>', $description);

    }

    echo "<table border='1'>";
    echo "<tr>";
    echo "<td> $title  </td>";
    echo "</tr>";
    echo "<tr>";
    echo "<td class = 'td1'> $description </td>";
    echo "</tr>";
    echo "</table>";

}

By the way, try using PDO or mysqli_ instead of regular mysql_ function.

David Bélanger
  • 7,400
  • 4
  • 37
  • 55
0

$reg_exUrl isn't echoed anywhere. So, your a href isn't appearing

Paul Dessert
  • 6,363
  • 8
  • 47
  • 74