views:

71

answers:

7

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.

Any suggestions?

Needs to be in PHP

+2  A: 

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.

Gordon
care to explain the downvote?
Gordon
@Gordon: same thing happened to my answer too. Looks like it's poor sportsmanship on someone's behalf. +1 from me for offering a valid non-regex solution, anyway.
Andy E
+2  A: 
preg_replace("/[0-9]/", "", $string);
System
Even this would match all digits, I guess it would be faster with the asterisk after the paranthesis, like in my answer.
faileN
It's not going to make much difference in speed using an astrisk vs not... And even at that, you're talking about a time value with 4 zeros after the decimal point anyway (0.00001 seconds or so), so unless you're doing it in a loop (a large loop), there's no point in trying to optimize a statement like this...
ircmaxell
This doesn't remove spaces
M42
Space removing wasn't the main point of view. But it's really easy to do that too. Just put space into brackets: [0-9 ]
System
+2  A: 

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.

Gordon
care to explain the downvote?
Gordon
+1  A: 
$str = preg_replace("/^[0-9 ]+/", "", $str);
M42
This would say, that the numbers have to be on the left side, and that there must be at least one number. This fits for the example he provided, but in general this solution wouldn't work. What about strings like "AM 23423NNfB"? You couldn't remove the numbers with your regex.
faileN
It answers the request of the op, he didn't say anything about what there is after PM.
M42
He said. "I've got a string LIKE...." And the headline of the topic says generally: Remove spaces from string. So I understand "ANY String".
faileN
+3  A: 
echo trim(str_replace(range(0,9),'',' 23 PM'));
Mark Baker
+1. very literal answer to the question: remove digits and trim.
Gordon
Literal is sometimes the best option, without further description from the OP.... and my solution wasn't much different to your own
Mark Baker
A: 

Regex

preg_replace('#[0-9 ]*#', '', $string);
faileN
You don't remove the spaces
M42
Spaces will be removed now.
faileN
+1  A: 

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

$pm = substr("  23 PM", -2); // -> "PM"
Andy E
upvoting this to compensate unjustified downvote and also because the OP is not clear about the strings he expects and Andy explicitly stated what the code above does.
Gordon