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

编程入门 行业动态 更新时间:2024-10-27 00:26:56
本文介绍了如何从字符串中删除所有数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想删除字符串[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.

更多推荐

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

本文发布于:2023-06-13 17:45:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/686750.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!