73

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 (á,ñ,ž...).

1

6 Answers 6

188

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.
Sign up to request clarification or add additional context in comments.

1 Comment

What about a . ? It's a number.
60

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.

2 Comments

This is smarter and shorter than the accepted solution, no?
What you need to know is that \d is all numbers in UTF-8 not only 0123456789 but also that in other languages.
7

Use Predefined Character Ranges also known as Character Classes:

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

2 Comments

I know I can google it anyhow it would be nice to have in the answer what are PCRs... Does this catch the Western Arabic chars mentioned in other answer?
You can use the PCR [:nd:] instead of [:digit:]
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.

1 Comment

+ after \d is exessive. It's obvious that zero digits cannot be replaced
-1

Alternatively, you can do this:

$words = trim($words, " 1..9"); 

2 Comments

What? Trim only works on the beginning and the end of a string. It would not cover cases like hello12 world.
I agree this unexplained answer is not reliable if a number exists in between two non-numbers.
-2

Regex

 $words = preg_replace('#[0-9 ]*#', '', $words); 

1 Comment

This answer removed numbers and spaces, but the asker does not want that behavior and never asked for it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.