php 如何从字符串中删除所有数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14236148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:54:50  来源:igfitidea点击:

How to remove all numbers from string?

phpregex

提问by Gago Design

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

我想从字符串 [0-9] 中删除所有数字。我写了这段有效的代码:

$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).

我想找到一个更优雅的解决方案:1 行代码(IMO 编写好的代码很重要)。

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

我在 stackoverflow 中找到的其他代码也删除了变音符号 (á,?,?...)。

回答by dan-lee

For Western Arabic numbers (0-9):

对于西方阿拉伯数字 (0-9):

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

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

对于包括西方阿拉伯语(例如Indian在内的所有数字:

$words = '????';
$words = preg_replace('/\d+/u', '', $words);
var_dump($words); // string(0) ""
  • \d+matches multiple numerals.
  • The modifier /uenables unicode string treatment. This modifier is important, otherwise the numerals would not match.
  • \d+匹配多个数字。
  • 修饰符/u启用 unicode 字符串处理。这个修饰符很重要,否则数字将不匹配。

回答by hsz

Try with regex \d:

尝试使用正则表达式\d

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

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

\d是一个等价物,[0-9]它是从0到 的数字的等价物9

回答by Veger

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

使用一些正则表达式,如[0-9]\d

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

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

您可能想阅读preg_replace() 文档,因为它直接显示在那里。

回答by NaveenDA

Use Predefined Character Ranges

使用预定义的字符范围

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

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

回答by Dimpal Gohil

Regex

正则表达式

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