PHP: How to Get all the Numbers out of an Alphanumeric String? CodeUnit 07 MAY 2010

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! :)

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.