Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
176 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...