PHP – Remove numbers found in a string

I was coding today and i needed to remove all occurrence of numbers in a given string.
I’m going provide two solutions it is up to you to choose which best suite you.

Method 1

create an array populated with number 0-9 then use PHP str_replace function to do the search and replace.
Here is a simple function for it.


function remove_numbers($string) {
    $num = array(0,1,2,3,4,5,6,7,8,9);
    return str_replace($num, null, $string);
}

E.g


echo remove_numbers('123Goat435'); // Goat

Method 2

Using Regex IMO is far better – less code.


$string = preg_replace('/[0-9]+/', '', $string);

Rewriting the function above to use regular expression becomes;


function remove_numbers($string) {
   return preg_replace('/[0-9]+/', null, $string);
}
Don’t miss out!
Subscribe to My Newsletter
Invalid email address