Page 1 of 1

Removing alpha characters from string

Posted: Wed Feb 20, 2008 10:47 am
by bill1one
I have a variable that contains a string of alpha and numeric characters, such as "Om3745". Is there a simple way in PHP to remove the alpha characters from the string? I've tried using substr(), but since the number of alpha characters before the number varies, it doesn't work consistently.
Thanks for any help.
Bill

Re: Removing alpha characters from string

Posted: Wed Feb 20, 2008 11:02 am
by liljester
Looks like you want to use a RegEx for this. Try preg_replace().

Code: Select all

$new_string = preg_replace("/[^1234567890]/", "", "Om3745");
this will replace anything that isnt a number with "".

Re: Removing alpha characters from string

Posted: Wed Feb 20, 2008 12:45 pm
by John Cartwright

Code: Select all

preg_replace("/[^\d]/", "", "Om3745");
Simpler :)

Re: Removing alpha characters from string

Posted: Wed Feb 20, 2008 12:48 pm
by liljester
indeed :)