Archive for July 27th, 2010

How to remove the numbers from a string with PHP

Tuesday, July 27th, 2010

I’ve recently looked for a way to remove numbers from a string using what is available in php.
Crawling trough the net first thing I found was using the php code:

<?php
function remove_numbers($string) {
$vowels = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", " ");
$string = str_replace($vowels, '', $string);
return $string;
}
$string='This string will have all numbers removed - 213 555 3930';
echo remove_numbers($string);
?>

Though this is not a bad approach it takes too much code to do a very simple task thus I googled around fod a better solution and found some examples which I used as a basis to come up with exactly what I was looking for, so enough jabberish here is the code to remove all numbers from a string:

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

Same is also possible using ereg_replace in older < 4.x php releases, though it’s completely depreciated now in php 5 >.
There should be plenty of other ways to remove numbers from a variable string, hence any user suggestions are very welcome!