从Mysql Row中提取Url

时间:2012-10-12 18:10:01

标签: php

人们上网并提交一篇文章,其中包含标题和说明。人们通常包含链接,但它们显示为基本文本。我想要一种方式,当人们包含网址时,它被认为是一个工作链接。我编写了一个代码,但它只扫描一行,似乎在实际的表中不起作用,因为它在表外回显。

基本上......我想要一个表格,当提交链接时,会创建一个超链接。有任何想法吗?    下面这个更新的代码保持不变。

我的代码如下:

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

}

2 个答案:

答案 0 :(得分:0)

这是因为您在使用preg_replace ...

进行替换之前打印出来

将你的preg放入你的循环中:

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

}

顺便说一句,尝试使用PDO或mysqli_而不是常规的mysql_函数。

答案 1 :(得分:0)

$reg_exUrl不会在任何地方回应。因此,您的a href没有出现