A lovely medley of Queen songs for the piano

random-posts-on-fluffed-vision

I came across this a few days ago and grabbed the sheet music for it almost immediately.  Possibly one of the best Queen medelys for solo piano I have ever come across.


Share this post:
read more

Get the values of an array of radio buttons – jQuery

Getting the value of a group of radio buttons is relatively straightforward, but what happens if you have more than one set?

I’ll start with a simple example of how to gather the data from a single set of radio buttons.

We’ll use this as our working example:

<div class="form-group">
  <div class="form-check form-check-inline">
    <input class="form-check-input checkMe" type="radio" name="amIChecked" value="yes">
    <label class="form-check-label" for="amIChecked">Yes</label>
  </div>
  <div class="form-check form-check-inline">
    <input class="form-check-input checkMe" type="radio" name="amIChecked" value="no">
    <label class="form-check-label" for="amIChecked">No</label>
  </div>
</div>

 

The jQuery to gather these fields would look something like this:

<script>
  jQuery(".checkMe").change(function(e) {
    e.preventDefault();
    const result = $("input[name='amIChecked']:checked").val();

    alert(result);

  })
</script>

In the above code, we are listening for a change event on the “checkMe” class.  At this point, we have asked the browser to provide the value of the input with the group name of “amIChecked”.

But what would happen if we were to produce a list, all ending in radio buttons?  If we adopted the above code, we would end up with only the result of the last set of radio buttons that the browser produced as it would keep re-attaching itself to the elements as they are rendered.  In this situation, we need to add something unique to each one.

I will assume at this point the list that your app is producing is being produced by a call to a database or similar.  If it isn’t and you just have a hard-coded list, this can still apply.

We need to take another approach to this to get this to fire correctly.  If you have been trying to do this with a similar method, then you will realise that applying the above method using a tweak of the above will produce hit and miss results.

The best way to approach this now is with a function.

Modified HTML:

<form id="{{ $thisRow->id }}">
  <div class="form-group"> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id="{{ $thisRow->id }}" name="amIChecked" onclick="clickedRadio('{{$rowID->id}}','yes')"> 
      <label class="form-check-label" for="amIChecked">Yes</label> 
    </div> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }}  name="amIChecked" onclick="clickedRadio('{{$rowID->id}}','no')"> 
      <label class="form-check-label" for="amIChecked">No</label> 
    </div> 
  </div>
</form>

I’m using the amazing Laravel framework in my project, so my ID is being produced in the Blade template using Laravels {{ }} syntax.  <?=$row->id;?> if you’re using vanilla PHP would be fine too.

You may notice I have also I have added <form> tags to each of the iterations in the loop.  This is because browsers will tend on only default the “checked” option (if you are using it) to the last iteration if everything has the same name value.  By adding <form> tags with a unique name, the browser treats all iterations as a single form.

Our function sends the row ID and the value to the jQuery for you to do with as you need.  With this in mind, there is no need to have the value=”” tags anymore, as they have been hardcoded in.

Now the modified jQuery:

<script> 
function clickedRadio(rowID, value)
    {
        alert(rowID + " : " + value);
     } 
</script>

With every click you should now get a row ID from your database (or whatever unique identifier you have chosen), and its value.  In this case, it will be yes or no, but it could be cats/dogs, on/off etc.

You aren’t limited to just two radio buttons using this method either.  This can be expanded to multiple values by just adding them in.

For example, this would be just as effective:

<form name="{{$rowID->id}}">
  <div class="form-group"> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','1')"> 
      <label class="form-check-label" for="userValue">Yes</label> 
    </div> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','2')"> 
      <label class="form-check-label" for="userValue">No</label> 
    </div>
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','3')"> 
      <label class="form-check-label" for="userValue">No</label> 
    </div> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','4')"> 
      <label class="form-check-label" for="userValue">No</label> 
    </div> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','5')"> 
      <label class="form-check-label" for="userValue">No</label> 
    </div> 
  </div>
</form>

Have fun!

Share this post:
read more

Laravel Error: 1071 Specified key was too long

laravel-framework-help-and-guide

We’ve all been there.  We’ve installed a fresh new Laravel installation, come to do the migrations and hit the dreaded error message saying our email key was too long.

This is the message in question:

[IlluminateDatabaseQueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique(email))

Thankfully, its really easy to fix.

Find the file: [your webroot]/app/Providers/AppServiceProvider.php

It will look like this from the default installation:

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Simply change to look like this:

<?php


namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesSchema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

.. and all will be well 🙂

 

Share this post:
read more

Adding tabbed panels to Bootstrap – No jQuery

A great little piece of functionality built into Bootstrap is the ability to clear up some screen space using panels cascaded behind each other in tabs.  The best part is, it’s super easy to implement.

Here’s the code:

<ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
    <li class="active"><a href="#tab1" data-toggle="tab">Tab 1</a></li>
    <li><a href="#tab2" data-toggle="tab">Tab 2</a></li>
    <li><a href="#tab3" data-toggle="tab">Tab 3</a></li>
    <li><a href="#tab4" data-toggle="tab">Tab 4</a></li>
    <li><a href="#tab5" data-toggle="tab">Tab 5</a></li>
</ul>
<div id="my-tab-content" class="tab-content">
    <div class="tab-pane active" id="tab1">
        <h1>Tab 1</h1>
    </div>
    <div class="tab-pane" id="tab2">
        <h1>Tab 2</h1>
    </div>
    <div class="tab-pane" id="tab3">
        <h1>Tab 3</h1>
    </div>
    <div class="tab-pane" id="tab4">
        <h1>Tab 4</h1>
    </div>
    <div class="tab-pane" id="tab5">
        <h1>Tab 5</h1>
    </div>
</div>

The above code will leave you something looking like this:

bootstrap-tab-loader

Feel free to use, copy and modify this code as you need to.

Share this post:
read more

Getting the ID of draggable and droppable elements – jQuery

jQuery’s drag and drop functionality is fantastic and adds excellent interactivity to your web application.  However, it can be a little confusing, so here are some straightforward examples that should get you off to a flying start when venturing into the world of drag and drop.

First, we need a few things to move around, so let’s create some:

<div id="div_01" class="draggable">Div 01</div>
<div id="div_02" class="draggable">Div 02</div>
<div id="div_03" class="draggable">Div 03</div>
<div id="div_04" class="draggable">Div 04</div>
<div id="div_05" class="draggable">Div 05</div>

You’ll need to get these in the context of your web page.

Next, we need somewhere to drop them:

<div id="dropzone_1" class="dropzone" style="height:100px;width:100px;border:1px solid black"></div>
<div id="dropzone_2" class="dropzone" style="height:100px;width:100px;border:1px solid black"></div>
<div id="dropzone_3" class="dropzone" style="height:100px;width:100px;border:1px solid black"></div>

I’ve used inline styles in the example above in case you are copying and pasting into a test HTML page of your own.  Inline styling isn’t great in a production environment; a separate style sheet is always better.  I’ve also assumed, that you have loaded the jQuery / jQuery UI version[s] of your choice onto the page by this point as well.

Making these elements draggable and droppable is easy.  Just add a function that covers both scenarios and then build upon them.

$(function () {
    $(".draggable").draggable();
    $(".dropzone").droppable();
});

At this point, you should be able to grab you divs and move them around the page.  They won’t do anything aside from move around the page, but it’s quite a novelty the first time it happens successfully!

It’s at this point the language used by jQuery can be a little bit confusing.  “Draggable” is obvious; it is something that can be dragged around the screen, its when you get to “droppable” that people sometimes run into confusion.  “Droppable” suggests you are dealing with something that once you start dragging around, is then available to be dropped, however, this isn’t the case.  “Droppable” by jQuery’s definition is the area that you drop a draggable.  The draggable itself, contains the drop event, whereas the droppable is just a static place your draggable gets dropped.

Confused yet? Don’t be; it’s effortless when you see it broken down.

Doing something with my draggable and droppable.

Take a look at this extended version of the code snippet above.  What you see below is taken directly from one of my live projects, so will need to be customised to suit your project:

$(function () {
    $(".draggable").draggable(
        {
            start:
                function (event, ui) {
                    $(this).css("z-index", 10);
                }
        }
    );
    $(".dropzone").droppable({
        drop: function (event, ui) {

            const dropZoneID = $(this).attr('id');
            const droppedItemID = ui.draggable.attr("id");

            /* 
             Do something with your newly gathered information
             */
        }
    });
});

So what is going on in the code above?  Let’s start with the draggable.  There are various events associated with the draggable.  Notably, these are start, stop and drag.  In the example above I’ve used the start event to bring the item, I’m dragging to a z-index of 10.  With my Bootstrap projects, I’ve found this handy to ensure the thing I’m dragging around remains at the top.  If I don’t set this index with Bootstrap, the draggable can end up going behind some of the other elements.

You can find a full reference to jQuery draggable here.

Lovely, but the exciting part comes when you drop these draggable.

The two critical pieces of information you need when dealing with draggable items and dropzones [and this may seem obvious] are, what you’ve dropped and where you’ve dropped it.  This is achieved using the “drop” event inside the droppable.  Here, I have created two constants [variables are also fine] that will gather this information.

A great way to visualise this if you are starting out with these is to add a test div, so you can see what’s happening.

Create a div, like this:

<div id="testDropDiv"></div>

Then in your code, add the following:

$(".dropzone").droppable({
        drop: function (event, ui) {

            const dropZoneID = $(this).attr('id');
            const droppedItemID = ui.draggable.attr("id");

            $("#testDropDiv).empty()
                     .append("I've just dropped div with ID: " + droppedItemID + " Onto: " + dropZoneID);

        }
    });

Which should then update each time you drop one of your draggable onto a dropzone.

The reference for jQuery droppable is available here.

I hope that gives a little bit of an insight into jQuery’s draggable and droppable.  This short introduction has only just scratched the surface of what is achievable.  I would recommend you have a look at the jQuery UI website to see some more examples.

Share this post:
read more

Recipe Review: The Pioneer Woman; Kicked-Up Tater Tot Hotdish

pioneer-woman-hotdish-review

I really enjoy watching The Pioneer Woman on the Food Network.  Good wholesome food that is easy to make.  For most home cooks, not interested in gourmet cooking, this is a dream come true.

For those of you that have no idea what I’m talking about; Ree Drummond, aka The Pioneer Woman, is an American TV celebrity chef, based out on a ranch in America. Ree’s emphasis is on good quality, simple food that is both easy to cook and to eat.  There are quite literally hundreds of recipes on her site (see link at the bottom), including starters, mains, desserts and sharing platers.  Ree’s website contains something for everybody.

Over the years I have tried dozens of her recipes and loved every single one of them.  So why the sudden review?  Well, I ventured into the realms of the hotdish (Americanism for a casserole for those that are wondering), and for the first time, I was disappointed.

Now, let’s be clear, this has nothing to do with the recipe.  The ingredients and the method are flawless.  What it does highlight, is the distinct difference in pallets between the UK and American citizens.  Reason; The sheer amount of cheese deployed in this savory dish.  I made the Kicked-Up Tater Tot hotdish, and there is cheese everywhere.  Cheese in the meat and cheese at the top.  When you combine this with the milk, sour cream and butter, it all starts to get sickly.

Perhaps it is just my palate, but my advice would be, if you don’t go for extremely sickly savory dishes, then avoid this one.

That said, this is only my opinion of one dish.  Ree’s food is fantastic, and I would recommend anyone, and everyone, try her recipes.

As a side note:

I did love the idea of using the tater tots (which are like potato croquet if you are British) atop a meal and then baked, so I modified the concept slightly.  Having not been able to eat the Ree version, I remade it using a thick Bolognese at the bottom, then covered with the potato, then added a topping of grated cheese.  I baked the whole thing in the oven for 35 minutes and then crisped the top off under the grill.  The potato croquet made an excellent substitute for the spaghetti carbs in a spaghetti bolognese, and the whole dish was very delicious.  I served it with a side of homemade garlic ciabatta.

 

Resources:

The Pioneer Woman Website

Kicked-Up Tater Tot hotdish- The Recipe

Share this post:
read more

Moths – Why do they always fly toward artificial light?

moths-and-atrificial-light

Moths and other flying insects will naturally gravitate toward a source of light.  Sadly, if this source of light is in the form of a flame, rather than a bulb, it usually means certain death to boot.  So why do they do it?

Moths and their behaviour towards light have fascinated me for a long time, so I’ve been reading up on the subject.  However, it has not been an easy topic to resolve, by a long, long way.

Theory 1 – Transverse Orientation

Transverse Orientation is a popular theory on the internet.  Moths using the light of the moon to navigate is an old theory.  By keeping the lunar glow in the same position, relative to themselves as they fly, moths can keep a pretty straight line.  You have to bear in mind that relative to the moon and it’s movements, moths are insignificant.  As far as the moth is concerned, the moon is a fixed object in the sky.

The Transverse Orientation model goes on to suggest that the problem this causes for moths and other insects, is the new distance to the light sources they are finding.  The moon is a long way away [citation needed], whereas artificial light sources are not [citation: my monitor is only 20″ from my face].

Let’s say that a moth keeps the moon on the left when flying.  Even better, let’s say that a moth is finding a straight path by keeping itself perpendicular to the moon, but then finds an artificial light source.  What will happen?

Here comes the merry go round.

A little bit of Newton

swingballAs analogies go, this isn’t great, but I’m going to try it like this.  Newton’s first law of motion states [broadly] that an object travelling in a given direction, will continue to do so unless another force acts upon it.  Imagine then a ball on a piece of string being swung around and around above your head.  If the string were to disappear at any given point, the ball would disappear off into the distance.  No longer would it be a ball in a circular motion, it would head off in a straight line.  The reason it doesn’t while the string is attached is that the string is providing a force which is keeping the ball perpendicular to the strings point of origin.  In this particular case, the root point is your head.

I would also like to apologise for the terrible stock photo demonstrating a ball on a string in circular motion.  It’s amazingly hard to find a stock photo of somebody swinging a ball around their head.  If anybody would like to take one and send it in, I will be happy to replace this one.

Well, we have our moth who is trying to fly in a straight line.  The moth sees an artificial light and moves toward it [see theory 3: phototaxis].  Now, to fly in a straight line, the moth has to keep the light 90 degrees to its left.  This flight pattern works until the moth has flown a tiny amount. However, then the light source shifts angle because it’s close, relative to the moth, so more adjustments are needed.  Ok, the moth thinks, I need to bear left slightly to maintain my 90-degree angle to the light.  These adjustments work for another tiny amount of flight, and the same happens again.

We could continue this into the thousands of words, but by now you should see what is happening.  The moth is permanently adjusting its coordination and flight path, which to the moth is a straight line.  However, looking on from outside this frame of reference, we see a moth flying around and around the light in a continuous loop.

You can sometimes see the circular motions getting bigger and smaller as the moth experiments with different patterns to attempt to get this right.  These experimental motions often result in the moth running into the light source.

Running into the light source is OK if its a lightbulb, but not so OK if it’s a candle or fire.  Poor moth.

Theory 2 – Infrared Sex

The infrared sex theory is a puzzling one.  Personally, given all I have read, I don’t have a great deal of confidence in this theory.

It’s all about the wavelength.

Just as a sidenote, I’m really pleased that everything in the whole world, including biology is explained by some branch of physics.  Chemistry can now be explained at a quantum level, as too can biology.  This demonstrates that physics, is by far the best, most interesting and most relevent branch of science.

There are a handful of studies that suggest that the wavelength of certain lights, especially infrared (as emitted by an open flame), matches certain wavelengths emitted by the female moth’s sex hormones.  This theory is used to provide evidence of why male moths zoom straight over to these lights and jump on them.  I’m unsure about this though, as ultraviolet light is far more attractive to moths than infrared.

If it is true though that the males are trying to pounce onto these light sources because they think they are females, it could be potentially harmless.  That’s if it’s a lightbulb.

If it’s a candle or a fire.  Poor moth.

Theory 3 – Phototaxis

I like phototaxis as a theory.  Transverse Orientation does a pretty decent job at explaining the circular motion of the moths around light sources.  Sometimes, though, simpler is better.

Imagine that you are a moth.  Then imagine you are happily sitting on a branch in your bush or tree when a bird swoops down and lands.  You, being a moth, are naturally going to want to escape your place of resting as quickly as possible.

The problem; its nighttime and dark (we’re pretending you are also thousands of years into the past and there are no artificial lights).  So what do you do?  You need to make a split second decision about where you are heading.  Hello, Phototaxis.

Phototactic animals fall into two categories.  Positively phototactic and negatively phototactic.

I’m going to try again with an analogy, but have to say, its a little on the tenous side.

If there were such a thing a heat-taxis, then humans would be negatively heat-tactic.  If you put your hand onto something hot, your immediate instinct is to pull your arm away.  There is no conscious decision made here; it’s just something you do.  This is kind of how phototaxis works.  There is no conscious decision made; it’s just something that happened instinctively.  Phototaxis is an instinctive reaction to light.

Cockroaches are a great example of an animal that is negatively phototactic.  While scurrying around, eating the leftover nibbles from your floor in the dark is fun, somebody walking in an turning a light on, is not.  As soon as the light comes on, Cockroaches will instinctively head for the dark, and quickly.  Phototaxis also applies, but to a lesser degree, to earthworms.  This trait is a useful aid to worm farmers who can stop their worms from escaping by shining a bright light on top of the worm beds at night.

Moths are the opposite.  Moths are positively phototactic, meaning that in a dangerous situation, they will instinctively do the opposite to cockroaches and fly toward the light.

Back to our moth in a tree.  You are suddenly startled and need to flee.  If you flee left, right or down, you will likely hit something.  So, the only way to go is up.  But which way is instinctively up?  Well at night, with no other artificial light sources around, up, is towards the moon and stars.  Any other direction is dark.

Conclusion:

Having looked at multiple articles on this subject, I cannot conclude that any of these theories are correct.  Nobody else can either.

If I had to make a choice, I would conclude that as moths have had millions of years with no artificial light to evolve, it would seem logical they would need the light for escape and navigation.  Moths are nocturnal after all.  So my final answer is, it is a mix of both transverse orientation for one aspect of their lives, and phototaxis for their instinctive survivability.

If anybody can give me some more ideas about moths artificial light fetish, then please get in touch.  You can do this via the contact page.

Share this post:
read more

Piano Medley To Play At Christmas Time

christmas-medley-for-piano

If you’re like me and like a piano sing song at Christmas time, then you can’t beat a good, pre-compiled medley to play through.

After seeing this video on YouTube:

Here’s the playlist for the video:

  1. It’s Beginning to Look a Lot Like Christmas (0:01)
  2. Let it Snow (1:18)
  3. Winter Wonderland (2:35)
  4. Christmas Tree (3:59)
  5. Silent Night (4:55)
  6. The First Noel (6:55)
  7. Hark! The Herald Angels Sing (8:40)
  8. Joy to the World (9:50)

If like me you want to play this medley at Christmas, you can find the sheet music for all tracks as a single bundle, for sale, here.

I found it to be the perfect mix of soft, upbeat and classically “swingy” Christmas arrangments I’ve seen in a while.

Enjoy!

Share this post:
read more

Pasta / Bolognese with hidden vegetables – perfect for the kids

kid-friendly-pasta-sauce

We have multiple children and getting them all to eat the same veg at the same time is a bit of a nightmare, so I thought I’d try hiding a whole bunch of veg in some sauce to see if I could get away with it.  I did.

All kids seem to go through the “I’m not eating my vegetables” stage, so it’s not something I worry about, mainly.  However, they do still need to consume as many of the life-boosting plants as possible.  After poking around in the fridge, I found some veg that I thought would cook down well and decided to give this sauce a go.

You can make this with, or without, the meat element.  If you use the meat, you end up a with a tasty bolognese.  However, if you prefer just a light pasta sauce, it will work just as well without.  I’ve written the recipe in such a way as you can do either.

Ingredients:

  • 500g lean mince (optional, see below)
  • 2 carrots
  • 1 large onion
  • 1 leek
  • 2 peppers (red or yellow)
  • 2 sticks of celery
  • 2 x 400g cans of chopped tomatoes
  • 2 cloves of garlic
  • 1 tbsp caster sugar
  • 1 tbsp balsamic vinegar
  • salt & pepper
  • 300 – 400g spaghetti or penne pasta (dried)
  • A gulp of oil; olive or vegetable

Method:

  1. Chop the carrots, onion, leek and celery in pieces.  Smallish pieces, although the size doesn’t matter.  Getting everything around the same size is the most important thing here.
  2. Heat a glug of oil in a large non-stick pan and start to cook the above.  You are looking to soften these, not brown them, so an extended time over a lower heat is best.  Around 20 minutes.
  3. While these are cooking, deseed and chop the peppers and peel/chop the garlic.
  4. When the carrot, celery, onion and leek are softening, add the pepper and the garlic and continue to cook for a further 10 minutes.  Again, keeping the heat low so as not to burn the garlic.
  5. Add the tomatoes, sugar and balsamic vinegar, stir and bring to a boil.
  6. Reduce the heat down again and cook for a further 20 minutes.  The longer, the better here actually.  I put a lid on and cook for around 40-45 minutes.  If you don’t have a cover for your pan, add a little water every now and again if the sauce is looking a bit thick.
  7. While this is cooking, cook the pasta, according to the pack guidelines.
  8. Once everything is soft and melded together, blitz the mixture with either a hand blender (soup blender), or if you want a super thin hidden veg sauce, pop it in a food processor and blitz on high speed for a few minutes.  It may pay you to let it cool a bit before using the food processor option.
  9. While in the blender, or using a separate pan if you want to save time, brown the mince.  Get it nice and hot, and beautiful brown as this caramelisation adds a mass of flavour.
  10. Once you have some browned mince, a sauce and some cooked pasta, combine all in a pot and serve.

This dish is lovely with some grated parmesan on top.

I’m not a chef so the instructions may be a little awkward.  It may pay you to read through the method first and get everything done into your order.

Share this post:
read more

PHP – Validate a UK postcode

php-banner

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;
            break;
        }
    }

    return $valid ? $postcode : FALSE;
}

Usage:

if(isValidPostcode("thePostcodeToCheck"))
{
  // postcode is valid
}
else
{
  // postcode is not valid
}

 

Share this post:
read more

1 2 3 6