本文介绍了如何从字符串中删除所有数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想删除字符串[0-9]中的所有数字.我写了这段有效的代码:
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
我想找到一个更优雅的解决方案:1行代码(IMO编写漂亮的代码很重要).
I'd like to find a more elegant solution: 1 line code (IMO write nice code is important).
我在stackoverflow中找到的其他代码也删除了变音符号(á,ñ,ž...).
The other code I found in stackoverflow also remove the Diacritics (á,ñ,ž...).
推荐答案
对于西方阿拉伯数字(0-9):
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+
匹配多个数字. - 修饰符
/u
启用Unicode字符串处理.此修饰符很重要,否则数字将不匹配. \d+
matches multiple numerals.- The modifier
/u
enables unicode string treatment. This modifier is important, otherwise the numerals would not match.
这篇关于如何从字符串中删除所有数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!