php 如何使用 RegEx 从字符串中删除数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3363005/
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
How to remove numbers from a string with RegEx
提问by Click Upvote
I have a string like this:
我有一个这样的字符串:
" 23 PM"
I would like to remove 23so I'm left with PMor (with space truncated) just PM.
我想删除,23所以我只剩下PMor(空间被截断)PM。
Any suggestions?
有什么建议?
Needs to be in PHP
需要在 PHP 中
回答by Mark Baker
echo trim(str_replace(range(0,9),'',' 23 PM'));
回答by Gordon
Can do with ltrim
可以用 ltrim
ltrim(' 23 PM', ' 0123456789');
This would remove any number and spaces from the left side of the string. If you need it for both sides, you can use trim. If you need it for just the right side, you can use rtrim.
这将从字符串的左侧删除任何数字和空格。如果双方都需要它,则可以使用trim. 如果你只需要它的右侧,你可以使用rtrim.
回答by tomasbelusky
preg_replace("/[0-9]/", "", $string);
回答by Gordon
Can also use str_replace, which is often the faster alternative to RegEx.
也可以使用str_replace,这通常是 RegEx 的更快替代方法。
str_replace(array(1,2,3,4,5,6,7,8,9,0,' '),'', ' 23 PM');
// or
str_replace(str_split(' 0123456789'), '', ' 23 PM');
which would replace any number 0-9 and the space from the string, regardless of position.
无论位置如何,它都会替换字符串中的任何数字 0-9 和空格。
回答by Andy E
回答by Fidi
Regex
正则表达式
preg_replace('#[0-9 ]*#', '', $string);
回答by Toto
$str = preg_replace("/^[0-9 ]+/", "", $str);
回答by Dimpal Gohil
You can also use the following:
您还可以使用以下内容:
preg_replace('/\d/', '',' 23 PM' );

