Tag Archives: PHP

PHP – Validate a UK postcode


Returns a true/false against a UK postcode, as well as attempting to format it correctly.

There are a million versions of this code on the internet, but being true to my FluffedVision roots and treating this as my notebook, rather than a traditional blog, I’m noting this snippet down here.

function isValidPostcode($originalPostcode)
    $alpha1 = "[abcdefghijklmnoprstuwyz]";
    $alpha2 = "[abcdefghklmnopqrstuvwxy]";
    $alpha3 = "[abcdefghjkpmnrstuvwxy]";
    $alpha4 = "[abehmnprvwxy]";
    $alpha5 = "[abdefghjlnpqrstuwxyz]";

    $pcexp[0] = '/^('.$alpha1.'{1}'.$alpha2.'{0,1}[0-9]{1,2})([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$/';
    $pcexp[1] = '/^('.$alpha1.'{1}[0-9]{1}'.$alpha3.'{1})([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$/';
    $pcexp[2] = '/^('.$alpha1.'{1}'.$alpha2.'{1}[0-9]{1}'.$alpha4.')([[:space:]]{0,})([0-9]{1}'.$alpha5.'{2})$/';
    $pcexp[3] = '/^(gir)([[:space:]]{0,})(0aa)$/';
    $pcexp[4] = '/^(bfpo)([[:space:]]{0,})([0-9]{1,4})$/';
    $pcexp[5] = '/^(bfpo)([[:space:]]{0,})(c/o([[:space:]]{0,})[0-9]{1,3})$/';
    $pcexp[6] = '/^([a-z]{4})([[:space:]]{0,})(1zz)$/';
    $pcexp[7] = '/^ai-2640$/';
    $postcode = strtolower($originalPostcode);

    $valid = FALSE;

    foreach ($pcexp as $regexp)
        if (preg_match($regexp, $postcode, $matches))
            $postcode = strtoupper ($matches[1] . ' ' . $matches [3]);
            $postcode = preg_replace ('/C/O([[:space:]]{0,})/', 'c/o ', $postcode);
            preg_match($pcexp[7], strtolower($originalPostcode), $matches) AND $postcode = 'AI-2640';
            $valid = TRUE;

    return $valid ? $postcode : FALSE;


  // postcode is valid
  // postcode is not valid


Share this post:
read more

Explode a multi-dimensional array (PHP)


Sometimes you need to explode more than just a single dimension array.  In the case of a project I worked on recently, I was given this data, taken from MySQL in the form of a string.


So, this is four locations, with a respective distance.

The trick with splitting them up, using PHP explode(), is to do it in two parts.  In this case, I first want to split them into units of warehouse location and distance, which is achieved like this:

$firstArray= explode('|',$distanceData->distance);

This will then produce an array that looks like this:

array (size=5)
  0 => string 'bromsgrove:27.83' (length=16)
  1 => string 'crawley:153.34' (length=14)
  2 => string 'manchester:119.5' (length=16)
  3 => string 'peterborough:125.62' (length=19)
  4 => string '' (length=0)

The problem with this, of course, is that the delimiter is added to the end of every location that is concatenated onto the end of the string when the data is being produced, so the next step is to get rid of the last character, which [in this case and many others], will always be tagged onto the end of a string like this.  We can do this with PHP substr().

$distanceData = substr($distanceData,0,-1);

So now when the array is produced, it doesn’t have the empty slot at the end.

array (size=4)
  0 => string 'bromsgrove:27.83' (length=16)
  1 => string 'crawley:153.34' (length=14)
  2 => string 'manchester:119.5' (length=16)
  3 => string 'peterborough:125.62' (length=19)

We now have 4 arrays that all need exploding, so it’s simply a case of cycling through each with a foreach loop and creating a new exploded array each time:

foreach($firstArray as $key => $data)
   $distance[$key]= explode(':',$data);

Which will give the final result we are looking for, a fully split-up, two-dimensional array, created from a delimited string.

array (size=4)
  0 => 
    array (size=2)
      0 => string 'bromsgrove' (length=10)
      1 => string '27.83' (length=5)
  1 => 
    array (size=2)
      0 => string 'crawley' (length=7)
      1 => string '153.34' (length=6)
  2 => 
    array (size=2)
      0 => string 'manchester' (length=10)
      1 => string '119.5' (length=5)
  3 => 
    array (size=2)
      0 => string 'peterborough' (length=12)
      1 => string '125.62' (length=6)

Although this array is OK, it does still need some work to make it super easy to use.  This can be done by whittling it down further, whilst already inside the foreach loop.

First, initialise an array:

$hubDistance= array();

Then build this array as you loop through using the data provided from the explode.

foreach ($firstArray as $key => $data) {
    $distance[$key] = explode(':', $data);
    $hubDistance[$distance[$key][0]] = (float)$distance[$key][1];

This will strip out any of the unnecessary levels in the array and leave you with something like this:

array (size=4)
  'bromsgrove' => float 27.83
  'crawley' => float 153.34
  'manchester' => float 119.5
  'peterborough' => float 125.62

Which is much better!

I’ve explicitly called float on the numbers for this project, but PHP will typically sort this out for you.


I keep needing to use this on various projects, so I’ve whittled it down to a function if anybody needs to use it:

function stringToArray($string)

     * This relies on the string being in the format
     * a1:a1a¬b1:b1a¬c1:c1a¬ [etc]
     * Individual separator = :
     * Group / cluster separator = ¬

    $string = mb_substr($string,0 ,-1);

    $firstArray = explode("¬",$string);

    $cleanArray = array();

    foreach ($firstArray as $key => $data) {
        $innerArray[$key] = explode(':', $data);
        $cleanArray[$innerArray[$key][0]] = $innerArray[$key][1];

    return $cleanArray;


So if you input a string like this :

$inputString = "sw4:33¬sw5:44¬swnh4:23¬swnh5:0¬mw4:223¬mw5:233¬mwnh4:433¬mwnh5:45¬"

Then use the function:


You’ll end up with something that looks like this:

array (size=8)
  'sw4' => string '33' (length=2)
  'sw5' => string '44' (length=2)
  'swnh4' => string '23' (length=2)
  'swnh5' => string '0' (length=1)
  'mw4' => string '223' (length=3)
  'mw5' => string '233' (length=3)
  'mwnh4' => string '433' (length=3)
  'mwnh5' => string '45' (length=2)

Probably no use to anybody, but it’s there if you need it 🙂

Share this post:
read more

Disable and enable buttons (Bootstrap) using a jQuery extension

A nice easy way to disable and re-enable buttons [etc] in Bootstrap with a little extension to the jQuery library.

Add this into the js file, either a custom.js or the main jQuery class file.  Custom being better so it doesn’t get overwriten in the future.

    disable: function (state) {
        return this.each(function () {
            var $this = $(this);
            $this.toggleClass('disabled', state);

Then use like this:





Share this post:
read more

A list of PHP dateTime method date and time formatting option


PHP dateTime formatting list for reference.

  • d – The day of the month (from 01 to 31)
  • D – A textual representation of a day (three letters)
  • j – The day of the month without leading zeros (1 to 31)
  • l (lowercase ‘L’) – A full textual representation of a day
  • N – The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
  • S – The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well with j)
  • w – A numeric representation of the day (0 for Sunday, 6 for Saturday)
  • z – The day of the year (from 0 through 365)
  • W – The ISO-8601 week number of year (weeks starting on Monday)
  • F – A full textual representation of a month (January through December)
  • m – A numeric representation of a month (from 01 to 12)
  • M – A short textual representation of a month (three letters)
  • n – A numeric representation of a month, without leading zeros (1 to 12)
  • t – The number of days in the given month
  • L – Whether it’s a leap year (1 if it is a leap year, 0 otherwise)
  • o – The ISO-8601 year number
  • Y – A four digit representation of a year
  • y – A two digit representation of a year
  • a – Lowercase am or pm
  • A – Uppercase AM or PM
  • B – Swatch Internet time (000 to 999)
  • g – 12-hour format of an hour (1 to 12)
  • G – 24-hour format of an hour (0 to 23)
  • h – 12-hour format of an hour (01 to 12)
  • H – 24-hour format of an hour (00 to 23)
  • i – Minutes with leading zeros (00 to 59)
  • s – Seconds, with leading zeros (00 to 59)
  • u – Microseconds (added in PHP 5.2.2)
  • e – The timezone identifier (Examples: UTC, GMT, Atlantic/Azores)
  • I (capital i) – Whether the date is in daylights savings time (1 if Daylight Savings Time, 0 otherwise)
  • O – Difference to Greenwich time (GMT) in hours (Example: +0100)
  • P – Difference to Greenwich time (GMT) in hours:minutes (added in PHP 5.1.3)
  • T – Timezone abbreviations (Examples: EST, MDT)
  • Z – Timezone offset in seconds. The offset for timezones west of UTC is negative (-43200 to 50400)
  • c – The ISO-8601 date (e.g. 2013-05-05T16:34:42+00:00)
  • r – The RFC 2822 formatted date (e.g. Fri, 12 Apr 2013 12:01:05 +0200)
  • U – The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
Share this post:
read more

Setting a cookie value immediately – PHP

The way to set a cookie:

setcookie("COOKIE NAME", "COOKIE VALUE", time() + 3600 * 8 * 7);

This cookie will be in place when the page next refreshes/loads;

To work with an immediate value of the cookie, add this as well:

setcookie("COOKIE NAME", "COOKIE VALUE", time() + 3600 * 8 * 7);

Using the above method will shove the value of the cookie into the session variable version, as well as writing it where it should be ready for a page reload.

Share this post:
read more