PHP: How to Get all the Letters out of an Alphanumeric String? CodeUnit 21 APR 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 numbers from the string, leaving only the letters 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 letter part as that information tells you what hash of my name and surname computes to.

Now in order to grab the letters we are simply going to knock out all the numbers 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:

$letters = preg_replace('/[0-9]/','','LTTCRA003');

The result of this code will be ‘LTTCRA’, thanks to us replacing all the numbers with blanks.

And there you go. That’s one way of getting all the letters 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.

  • Samuel Omisakin

    or this preg_replace(“/[^a-zA-Z]/”, “”, $string);