PHP: How to Get all the Numbers out of an Alphanumeric String?

Given a registration code, or something important like that, which often contains information encoded in the alphanumeric string itself, it is sometimes quite useful to be able to simply strip out the letters from the string, leaving only the numeric part behind.

So for example, for a code that looks like LTTCRA003 (my old University student number in case you were wondering), it might be of use to pull out the digit part as that information tells you how many times the LTTCRA hash of name and surname has occurred before.

Now in order to grab the numbers we are simply going to knock out all the letters contained in the string and for that we will use preg_replace, a function which makes use of regular expression matching to make its string replacements.

So what exactly do we need to do in terms of code then?

Well, the regular expression itself is pretty simple (probably the most simple you can get), and put into code, this is what will solve our little problem for us:

$numbers = preg_replace('/[a-zA-Z]/','','LTTCRA003');

The result of this code will be ’003′, thanks to us replacing all the letters with blanks.

And there you go. That’s one way of getting all the numbers out of an alphanumeric string! :)

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , , , , , , . Bookmark the permalink.
    blog comments powered by Disqus