68

I'd like to remove all numbers from a string [0-9]. I wrote this code that is working:

$words = preg_replace('/0/', '', $words ); // remove numbers
$words = preg_replace('/1/', '', $words ); // remove numbers
$words = preg_replace('/2/', '', $words ); // remove numbers
$words = preg_replace('/3/', '', $words ); // remove numbers
$words = preg_replace('/4/', '', $words ); // remove numbers
$words = preg_replace('/5/', '', $words ); // remove numbers
$words = preg_replace('/6/', '', $words ); // remove numbers
$words = preg_replace('/7/', '', $words ); // remove numbers
$words = preg_replace('/8/', '', $words ); // remove numbers
$words = preg_replace('/9/', '', $words ); // remove numbers

I'd like to find a more elegant solution: 1 line code (IMO write nice code is important).

The other code I found in stackoverflow also remove the Diacritics (á,ñ,ž...).

kenorb
  • 137,499
  • 74
  • 643
  • 694
Gago Design
  • 952
  • 2
  • 9
  • 16
  • 1
    * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Jan 09 '13 at 13:24

6 Answers6

170

For Western Arabic numbers (0-9):

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

For all numerals including Western Arabic (e.g. Indian):

$words = '१३३७';
$words = preg_replace('/\d+/u', '', $words);
var_dump($words); // string(0) ""
  • \d+ matches multiple numerals.
  • The modifier /u enables unicode string treatment. This modifier is important, otherwise the numerals would not match.
dan-lee
  • 14,094
  • 5
  • 50
  • 76
55

Try with regex \d:

$words = preg_replace('/\d/', '', $words );

\d is an equivalent for [0-9] which is an equivalent for numbers range from 0 to 9.

hsz
  • 143,040
  • 58
  • 252
  • 308
6

Use some regex like [0-9] or \d:

$words = preg_replace('/\d+/', '', $words );

You might want to read the preg_replace() documentation as this is directly shown there.

Veger
  • 35,906
  • 11
  • 106
  • 114
2

Use Predefined Character Ranges

echo $words= preg_replace('/[[:digit:]]/','', $words);

Naveen DA
  • 3,733
  • 4
  • 37
  • 51
0

Regex

   $words = preg_replace('#[0-9 ]*#', '', $words);
Dimpal Gohil
  • 223
  • 2
  • 10
0

Alternatively, you can do this:

$words = trim($words, " 1..9");
  • What? Trim only works on the beginning and the end of a string. It would not cover cases like `hello12 world`. – Eduard Feb 25 '22 at 21:48