Removing alpha characters from string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bill1one
Forum Newbie
Posts: 8
Joined: Thu May 24, 2007 2:12 pm

Removing alpha characters from string

Post 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
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Re: Removing alpha characters from string

Post 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 "".
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Removing alpha characters from string

Post by John Cartwright »

Code: Select all

preg_replace("/[^\d]/", "", "Om3745");
Simpler :)
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Re: Removing alpha characters from string

Post by liljester »

indeed :)
Post Reply