Tag Archives: preg_replace

PHP: Use REGEX to Ensure that your received Variable is a Number CodeUnit 20 MAY 2011

It is a good idea to check that the variables your script is receiving are in fact of the correct type in terms of value passed. For example, when receiving some sort of record ID value, 99% of the time we are expecting a numeric value. A simple method to ensure that the variable to be processed is indeed numeric, is through the use of a simple REGEX statement applied using the preg_replace PHP function.

As an example, let’s process a user ID passed to us via a POST to our script:

$userid = (key_exists('user-id', $_POST)) ? preg_replace("@[^0-9-]@", '', $_POST['user-id']) : '-1';

What the above does is first check that the user-id is indeed present in the $_POST variable. If it isn’t, set our internal variable to -1. If it is present, replace all characters that don’t fall within the set of 0 to 9, excluding dashes, with a blank. This is assigned back to our variable for internal use.

So a simple check to guarantee that we’ve received either a positive (2) or negative (-2) number!

Nifty.

PHP: Strip Non-Alphanumeric Characters out of a String CodeUnit 26 NOV 2010

Sometimes it comes in quite handy to strip out all the non-alphanumeric characters from a given string. Of course, we could just use a bog standard preg_replace with a valid regex to achieve this, though the result of doing this might result in a non-readable resulting string.

For example:

Sitting in a café, Jørgen thought the wallpaper too passé

could potentially become

Sitting in a caf Jrgen thought the wallpaper too pass

Unfortunately this string has lost too much of its meaning with the simple strip, meaning we should pad out our preg_replace approach with another function that removes all the Accents off letters first.

So running the string through the removeAccents followed by the regex would result in this:

Sitting in a cafe Jorgen thought the wallpaper too passe

In other words, much more readable. And the code to do this for us?

function removeAccents($str)
{
  $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', '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 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
  return str_replace($a, $b, $str);
}

$newstring = preg_replace("/[^a-zA-Z0-9.s]/", "", removeAccents($oldstring));

where $oldstring is the string containing the non-alphanumeric characters.

So in summary, easy peasy stuff this.

PHP: How to Remove or Replace Strings from the Front and End of a Value CodeUnit 02 JUL 2010

Today’s little PHP hint is a pretty simple one, but one worth tackling if you are looking for a quick and easy way to strip a particular string pattern off the front and end of a value.

What we will make use of is of course PHP’s built in preg_replace functionality, basically one of the wrapper functions that brings regular expression manipulation to PHP.

Now to start off, we need to specify the string pattern we wish to search for off the front of our value. To do this we make use of the ^ regex control character that denotes the search to begin from the start of a string. To locate a string pattern off the end of our value, we make use of the $ regex control character which likewise, tells the search to commence at the back of the given string value.

We then place our two patterns in a search array, before moving on to define our replace array. Now at this stage you can choose: if you want to simply strip these patterns off the value, then simply match the search patterns with the same amount of blank string values, otherwise insert the string values you wish to replace the patterns with.

Finally, we call the preg_replace function, feeding it our search and replace arrays, as well as the input value it is to work on.

In other words, we would have something like this:

$search = array ( "/^stringatstart /","/ stringatend$/");
$replace = array ('','');

echo preg_replace($search, $replace, "stringatstart Hello World! stringatend");

And there you go, a nice and simple way to strip off specific values at either end of a string! :)

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

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