Return mysql string using regex

Here is my code:

$sql = "SELECT `description` FROM `auctions` WHERE `description` REGEXP '[0-9]{10}'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
  echo $row["description"];
}

      

This returns a whole field description

, I just need to get the part that matches the REGEXP, how can I do it using php?

+3


source to share


2 answers


$sql = "SELECT `description` FROM `auctions` WHERE `description` REGEXP '[0-9]{10}'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
    preg_match('/\d{10}/', $row["description"], $match);
    echo $match[0];
}

      



+1


source


Try the following:

$results = array();
$sql = "SELECT `description` FROM `auctions` WHERE `description` REGEXP '[0-9]{10}'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
    // Checks for a match in the description and capture the match to $match
    preg_match("/[0-9]{10}/", $row['description'], $match);

    // Save the complete match (the ten digits) to the results array.
    $results[] = $match[0];
    // Or just echo them
    echo $match[0];
}

      



By the way, you should also take a look at prepared statements , specifically for preventing SQL injection.

0


source







All Articles