Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all numbers from string?

Tags:

regex

php

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

like image 545
Gago Design Avatar asked Jan 09 '13 13:01

Gago Design


People also ask

How do I remove numbers from a string in a Dataframe Python?

In the regular expression \d stands for "any digit" and + stands for "one or more". Thus, str. replace('\d+', '') means: "Replace all occurring digits in the strings with nothing".


2 Answers

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.
like image 169
dan-lee Avatar answered Sep 30 '22 12:09

dan-lee


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.

like image 45
hsz Avatar answered Sep 30 '22 11:09

hsz