Skip to content
PHP Logo

What is the best way to filter out non-numeric characters from a PHP variable?

When dealing with a PHP variable that may contain non-numeric characters, the best way to filter out these characters is by using the `preg_replace` function with a regular expression pattern that matches non-numeric characters. This function will replace all non-numeric characters with an empty string, effectively filtering them out from the variable.

php
// Example PHP code to filter out non-numeric characters from a variable
$variable = "123abc456";
$filtered_variable = preg_replace("/[^0-9]/", "", $variable);

echo $filtered_variable; // Output: 123456