-1

In the database table that I use for this script, the rows have characters (like ".", "_") with numbers together. How can I remove the characters and only fetch the numbers from the table? The php code that I use:

<html>
<head>
</head>   
<body>     

<table class="tbnar">
<tr>
<th>Enex</th> 
<th>Snex</th>
</tr>

 <?php

  include ("config.php");

  $sql = "SELECT Enex, Snex FROM sntab";
  $result = $conn->query($sql);
  if ($result->num_rows > 0) {

  $counter = 0;

   while($row = $result->fetch_assoc()) 
   {
        echo  "</td><td>". $row["Enex"] . "</td><td>" . $row["Snex"].   
            "</td></tr>";

            $counter++;
            if($counter % 33 == 0) { ?>
</table>

<table class="tbnar">
<tr>
<th>Enex</th> 
<th>Snex</th>
</tr>

 <?php }
    }
echo "</table>";

} else { echo "0 results"; }
$conn->close();
?>     
</table>               

    </body>
</html>
Max
  • 932
  • 1
  • 10
  • 20
  • You can use mysql replace in select query itself - https://dev.mysql.com/doc/refman/8.0/en/replace.html – Manikandan S Jul 06 '18 at 11:18
  • @Manikandan Replace doesn't work like that and even if it did i don't think the op want to change the database values – Dimitris Filippou Jul 06 '18 at 11:21
  • This article may help https://stackoverflow.com/questions/7688844/php-preg-replace-only-allow-numbers – Paul Jul 06 '18 at 11:22
  • @DimitrisFilippou I don't think so. In this case replace will work I feel. FYI please check this url once - https://www.w3schools.com/sql/trymysql.asp?filename=trysql_func_mysql_replace – Manikandan S Jul 06 '18 at 11:23
  • [OT] It's not a good practice to spit out html code with echo, consider using the short tags = and ?> and leave the html outside of php – carlduke Jul 06 '18 at 11:24
  • Thanks for your suggestions. – Max Jul 06 '18 at 11:35

1 Answers1

3

You can use a regex to do this

echo  "</td><td>". preg_replace('/[^0-9]+/','',$row["Enex"]) . "</td><td>" . preg_replace('/[^0-9]+/','',$row["Snex"]).   
        "</td></tr>";

This regex will remove every non-numeric character.

Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29