I have a string like this:
" 2开发者_开发知识库3 PM"
I would like to remove 23
so I'm left with PM
or (with space truncated) just PM
.
Any suggestions?
Needs to be in PHP
echo trim(str_replace(range(0,9),'',' 23 PM'));
Can do with 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
.
preg_replace("/[0-9]/", "", $string);
Can also use str_replace
, which is often the faster alternative to 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.
If you just want the last two characters of the string, use substr with a negative start:
$pm = substr(" 23 PM", -2); // -> "PM"
$str = preg_replace("/^[0-9 ]+/", "", $str);
Regex
preg_replace('#[0-9 ]*#', '', $string);
You can also use the following:
preg_replace('/\d/', '',' 23 PM' );
trim()
will allow a range of characters in the "character mask" parameter by using dot syntax.
Code: (Demo)
// v--------literal spaces
trim(" 23 PM", ' 0..9')
// ^^^^----all digits
// output: PM
精彩评论