如何使用RegEx从字符串中删除数字

时间:2021-09-16 18:02:30

I have a string like this:

我有一个像这样的字符串:

" 23 PM"

I would like to remove 23 so I'm left with PM or (with space truncated) just PM.

我想删除23,所以我留下PM或(空格截断)只是PM。

Any suggestions?

有什么建议么?

Needs to be in PHP

需要在PHP中

8 个解决方案

#1


62  

echo trim(str_replace(range(0,9),'',' 23 PM'));

#2


15  

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.

这将从字符串的左侧删除任何数字和空格。如果你需要双面,你可以使用修剪。如果您需要它在右侧,您可以使用rtrim。

#3


14  

preg_replace("/[0-9]/", "", $string);

#4


5  

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和字符串中的空格,无论位置如何。

#5


5  

If you just want the last two characters of the string, use substr with a negative start:

如果您只想要字符串的最后两个字符,请使用带负数的substr:

$pm = substr("  23 PM", -2); // -> "PM"

#6


3  

$str = preg_replace("/^[0-9 ]+/", "", $str);

#7


3  

Regex

正则表达式

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

#8


2  

You can also use the following:

您还可以使用以下内容:

preg_replace('/\d/', '',' 23 PM' );

#1


62  

echo trim(str_replace(range(0,9),'',' 23 PM'));

#2


15  

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.

这将从字符串的左侧删除任何数字和空格。如果你需要双面,你可以使用修剪。如果您需要它在右侧,您可以使用rtrim。

#3


14  

preg_replace("/[0-9]/", "", $string);

#4


5  

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和字符串中的空格,无论位置如何。

#5


5  

If you just want the last two characters of the string, use substr with a negative start:

如果您只想要字符串的最后两个字符,请使用带负数的substr:

$pm = substr("  23 PM", -2); // -> "PM"

#6


3  

$str = preg_replace("/^[0-9 ]+/", "", $str);

#7


3  

Regex

正则表达式

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

#8


2  

You can also use the following:

您还可以使用以下内容:

preg_replace('/\d/', '',' 23 PM' );