How to remove all numbers from string?

PhpRegex

Php Problem Overview


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

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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.

Solution 3 - Php

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.

Solution 4 - Php

Use Predefined Character Ranges

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

Solution 5 - Php

Regex

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

Solution 6 - Php

Alternatively, you can do this:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGago DesignView Question on Stackoverflow
Solution 1 - Phpdan-leeView Answer on Stackoverflow
Solution 2 - PhphszView Answer on Stackoverflow
Solution 3 - PhpVegerView Answer on Stackoverflow
Solution 4 - PhpNaveen DAView Answer on Stackoverflow
Solution 5 - PhpDimpal GohilView Answer on Stackoverflow
Solution 6 - PhpBohdan PukhovskyiView Answer on Stackoverflow