Category : PHP

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

How to show your latest blog posts on a non-WordPress page

wordpress-blog-header-fluffed-vision

Quite often on a website, there is a need to show your WordPress blog posts outside of the WordPress installation.  You may already have an HTML / PHP site, and you have decided to add a blog page, but want to show some of the posts on the front page (for example).  Luckily, WordPress makes this process as easy as adding a few lines of code to your pages.

You will need a little bit of familiarity with PHP, but realistically, anybody should be able to do it.

There are two things to do:

First, you need to tell your non-Wordpress page that you are going to be extracting information about your posts. So, at the top of the page add the following:

<?php 
  define('WP_USE_THEMES', false);
  require('/wp-load.php');
  query_posts('showposts=4');
?>

Let’s break this down a bit.

The first line tells WordPress that it won’t be needing to use any of its themes.  We are adding the posts to a page that we will assume is already using a stylesheet of its own, so we need the extracted WordPress information to blend in accordingly.

The “require” line will need to be relative to your wp-load.php, so if you have added your blog in the default WordPress directory, this line may end up as:

// If it's in a directory called "wordpress"

require('wordpress/wp-load.php');

// If you need to backtrack to server root to get to you sub-folder

require('../wordpress/wp-load.php');

The exact structure of this line is individual web server and code dependent so will need to be adjusted to suit your exact requirements.

The second line is pretty self-explanatory, it is telling the page to use the WordPress loader.  The loader is required whenever you call anything from WordPress, be it posts, pages, categories etc.

The third line is what we want to extract from the WordPress database.  In this case, we are pulling the lastest four posts.

Following this, we will need to display the posts on the page.  We do this using the standard WordPress API in the form of WordPress hooks.

So:

<?php while (have_posts()): the_post(); ?>

  <h4><?php the_title(); ?></h4>

  <?php the_excerpt(); ?>

  <p><a target="_blank" href="<?php the_permalink(); ?>">Read more...</a></p>

<?php endwhile; ?>

 

That’s it!

The first and last lines tell the page to show posts if there are posts available.  From there, it is just a list of standard WordPress hooks, which on the whole of quite explanatory.  While we are looping through four posts, for each of them, show the post’s title, the excerpt from the post – which can be adjusted in the WordPress admin panel – then add a link to read more.  This link will take the user to the main blog page.

Want to show the full post and not an excerpt from it? No problem.  Just replace “the_excerpt” with “the_content”.

Want to add the posts featured image as well?  No problem, include:

<?php
  if ( has_post_thumbnail() ) {
      the_post_thumbnail();
  }
?>

Here are some working examples:

An example snippet that would show the title of the post, along with the featured image and an extract of the content:

<?php while (have_posts()): the_post(); ?>
 <h4><?php the_title(); ?></h4>
 <p>
  <?php
    if ( has_post_thumbnail() ) {
      the_post_thumbnail();
    }
  ?>
 </p>
 <?php the_excerpt(); ?>
 <p><a target="_blank" href="<?php the_permalink(); ?>">Read more...</a></p>
<?php endwhile; ?>

An example snippet that will show the title, full post, but no image:

<?php while (have_posts()): the_post(); ?>
 <h4><?php the_title(); ?></h4>
 <?php the_content(); ?>
 <p><a target="_blank" href="<?php the_permalink(); ?>">Read more...</a></p>
<?php endwhile; ?>

If anybody would like to add some more code examples to the comments, I’ll be glad to see them and we’ll get them added to the main post to build up a little library of useful snippets.

 

 

 

Share this post:
read more

Explode a multi-dimensional array (PHP)

php-banner

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.

bromsgrove:27.83|crawley:153.34|manchester:119.5|peterborough:125.62|

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.

Update:

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:

var_dump(stringToArray($inputString);

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

PHP function to match worldwide VAT numbers

php-banner

From another site, but jotted down here for reference in the future:

function checkVatNumber( $country, $vat_number ) {
    switch($country) {
        case 'Austria':
            $regex = '/^(AT){0,1}U[0-9]{8}$/i';
            break;
        case 'Belgium':
            $regex = '/^(BE){0,1}[0]{0,1}[0-9]{9}$/i';
            break;
        case 'Bulgaria':
            $regex = '/^(BG){0,1}[0-9]{9,10}$/i';
            break;
        case 'Cyprus':
            $regex = '/^(CY){0,1}[0-9]{8}[A-Z]$/i';
            break;
        case 'Czech Republic':
            $regex = '/^(CZ){0,1}[0-9]{8,10}$/i';
            break;
        case 'Denmark':
            $regex = '/^(DK){0,1}([0-9]{2}[ ]{0,1}){3}[0-9]{2}$/i';
            break;
        case 'Estonia':
        case 'Germany':
        case 'Greece':
        case 'Portugal':
            $regex = '/^(EE|EL|DE|PT){0,1}[0-9]{9}$/i';
            break;
        case 'France':
            $regex = '/^(FR){0,1}[0-9A-Z]{2}[ ]{0,1}[0-9]{9}$/i';
            break;
        case 'Finland':
        case 'Hungary':
        case 'Luxembourg':
        case 'Malta':
        case 'Slovenia':
            $regex = '/^(FI|HU|LU|MT|SI){0,1}[0-9]{8}$/i';
            break;
        case 'Ireland':
            $regex = '/^(IE){0,1}[0-9][0-9A-Z+*][0-9]{5}[A-Z]$/i';
            break;
        case 'Italy':
        case 'Latvia':
            $regex = '/^(IT|LV){0,1}[0-9]{11}$/i';
            break;
        case 'Lithuania':
            $regex = '/^(LT){0,1}([0-9]{9}|[0-9]{12})$/i';
            break;
        case 'Netherlands':
            $regex = '/^(NL){0,1}[0-9]{9}B[0-9]{2}$/i';
            break;
        case 'Poland':
        case 'Slovakia':
            $regex = '/^(PL|SK){0,1}[0-9]{10}$/i';
            break;
        case 'Romania':
            $regex = '/^(RO){0,1}[0-9]{2,10}$/i';
            break;
        case 'Sweden':
            $regex = '/^(SE){0,1}[0-9]{12}$/i';
            break;
        case 'Spain':
            $regex = '/^(ES){0,1}([0-9A-Z][0-9]{7}[A-Z])|([A-Z][0-9]{7}[0-9A-Z])$/i';
            break;
        case 'United Kingdom':
            $regex = '/^(GB){0,1}([1-9][0-9]{2}[ ]{0,1}[0-9]{4}[ ]{0,1}[0-9]{2})|([1-9][0-9]{2}[ ]{0,1}[0-9]{4}[ ]{0,1}[0-9]{2}[ ]{0,1}[0-9]{3})|((GD|HA)[0-9]{3})$/i';
            break;
        default:
            return -1;
            break;
    }
   
    return preg_match($regex, $vat_number);
}

 

Share this post:
read more

PHP – Round a value up to the nearest multiple value

php-banner

round(), ceil() and the like to a good job of most things in PHP.

But what if you need to round the number up to the nearest 10 or nearest 15 etc.  This little function makes this easy:

function roundToNearestMultiple($value, $roundTo)
{
    $mod = $value%$roundTo;
    return $value+($mod<($roundTo/2)?-$mod:$roundTo-$mod);
}

Usage:

$number= roundToNearestMultiple($input, 10);

/* 
    Outputs:
      $input= 7 -> $number= 10
      $input= 85 -> $number= 90
*/

$number= roundToNearestMultiple($input, 15);

/* 
    Outputs:
      $input= 89 -> $number= 90
      $input= 1869 -> $number= 1875
*/

 

Share this post:
read more

Create a random string with PHP

php-banner

How to create a random string with PHP.

Step 1:

Include the following function somewhere.

function randomstring($length)
{
  $string = "";
  $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  for($i=0;$i<$length;$i++)
  $string.=substr($chars,rand(0,strlen($chars)),1);
  return $string;
}

I’ve only included upper and lower case characters here, but you can add anything to the $chars variable, and they will be included and picked at random.

Usage:

Just send the length of the string you want to return to the function when you call it, and it will return your random string.  So a random 15 character string would be:

$randomString= randomstring(15);

 

Share this post:
read more

How to capitalise the first word of each sentence – PHP

php-banner

So this can be a tricky one.  PHP has some excellent built-in functions for capitalising the first word of a string and capitalising all of the words in a string, but there are no built-in functions (that I’m aware of) that will capitalise the first word of each sentence.  This can be overcome using our old favourites, the regular expressions and preg_replace_callback() function.

$outputString = preg_replace_callback('/([.!?])\s*(\w)/', function ($matches) {
    return strtoupper($matches[1] . ' ' . $matches[2]);
}, ucfirst(strtolower($inputString)));

 

Share this post:
read more

Class to add some table functionality to FPDF

php-banner
<?php
require('fpdf.php');

class PDF extends FPDF
{
// Load data
function LoadData($file)
{
    // Read file lines
    $lines = file($file);
    $data = array();
    foreach($lines as $line)
        $data[] = explode(';',trim($line));
    return $data;
}

// Simple table
function BasicTable($header, $data)
{
    // Header
    foreach($header as $col)
        $this->Cell(40,7,$col,1);
    $this->Ln();
    // Data
    foreach($data as $row)
    {
        foreach($row as $col)
            $this->Cell(40,6,$col,1);
        $this->Ln();
    }
}

// Better table
function ImprovedTable($header, $data)
{
    // Column widths
    $w = array(40, 35, 40, 45);
    // Header
    for($i=0;$i<count($header);$i++)
        $this->Cell($w[$i],7,$header[$i],1,0,'C');
    $this->Ln();
    // Data
    foreach($data as $row)
    {
        $this->Cell($w[0],6,$row[0],'LR');
        $this->Cell($w[1],6,$row[1],'LR');
        $this->Cell($w[2],6,number_format($row[2]),'LR',0,'R');
        $this->Cell($w[3],6,number_format($row[3]),'LR',0,'R');
        $this->Ln();
    }
    // Closing line
    $this->Cell(array_sum($w),0,'','T');
}

// Colored table
function FancyTable($header, $data)
{
    // Colors, line width and bold font
    $this->SetFillColor(255,0,0);
    $this->SetTextColor(255);
    $this->SetDrawColor(128,0,0);
    $this->SetLineWidth(.3);
    $this->SetFont('','B');
    // Header
    $w = array(40, 35, 40, 45);
    for($i=0;$i<count($header);$i++)
        $this->Cell($w[$i],7,$header[$i],1,0,'C',true);
    $this->Ln();
    // Color and font restoration
    $this->SetFillColor(224,235,255);
    $this->SetTextColor(0);
    $this->SetFont('');
    // Data
    $fill = false;
    foreach($data as $row)
    {
        $this->Cell($w[0],6,$row[0],'LR',0,'L',$fill);
        $this->Cell($w[1],6,$row[1],'LR',0,'L',$fill);
        $this->Cell($w[2],6,number_format($row[2]),'LR',0,'R',$fill);
        $this->Cell($w[3],6,number_format($row[3]),'LR',0,'R',$fill);
        $this->Ln();
        $fill = !$fill;
    }
    // Closing line
    $this->Cell(array_sum($w),0,'','T');
}
}

$pdf = new PDF();
// Column headings
$header = array('Country', 'Capital', 'Area (sq km)', 'Pop. (thousands)');
// Data loading
$data = $pdf->LoadData('countries.txt');
$pdf->SetFont('Arial','',14);
$pdf->AddPage();
$pdf->BasicTable($header,$data);
$pdf->AddPage();
$pdf->ImprovedTable($header,$data);
$pdf->AddPage();
$pdf->FancyTable($header,$data);
$pdf->Output();
?>

 

Share this post:
read more

Using FPDF – Basic commands and explanations to suit

Creating PDF’s with PHP using FPDF.  This will get added to over time.

First, include the FPDF class.

require('fpdf.php');

Set up the page:

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);

Add a cell to the page.  Cells contain the elements on the page:

$pdf->Cell(20,10,"Some text to display on the page");

One thing to watch for is that this:

$pdf->Cell(20,10,"C1");
$pdf->Cell(20,10,"C2");
$pdf->Cell(20,10,"C3");
$pdf->Cell(20,10,"C4");

Will produce: C1    C2    C3    C4

To add some line breaks:

$pdf->Cell(20,10,"C1"); 
$pdf->Ln();
$pdf->Cell(20,10,"C2"); 
$pdf->Ln();
$pdf->Cell(20,10,"C3"); 
$pdf->Ln();
$pdf->Cell(20,10,"C4");

You can also add custom spacing to the line breaks:

$pdf->Ln(10);

So far we have:

require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(20,10,"Some text to output to the PDF");
$pdf->Ln();
$pdf->Cell(20,10,"Some more text to output to the PDF");

Now we need to output the PDF to something.  Browsers can be a bit fickle when displaying PDF’s on the screen:

$pdf->Output('../../temp/file.pdf','F');

The “F” flag tells the script to output the PDF as a file called file.pdf (temp is just the directory I’m using for testing and has no relevance to FPDF).

Flags also include “D”, which is to force a file to the browser with a download trigger and “I” which outputs the PDF inline.  I have found inline display of PDF’s from FPDF work best with the <object> flag within HTML.

Share this post:
read more

PHP ternary operators and how to use them

php-banner

I’ll add more to this note as I find the need.  Something I already use, but as of PHP7, there are a few little newbies that it doesn’t hurt to note down.

I like this one.  It replaces the isset() clause.

So this:

if(isset($_POST['something']){$something= $_POST['something'];}

Can now be written (in PHP7+):

$something= $_POST['something'] ?? "default";

The above fetches the POST content if it exists, and defaults to the ” ” enclosed value if it doesn’t.

Some more examples of ternary operators:

$isABigNumber = ($number < 1000 ? "Small Number" : "Big Number")

 

Share this post:
read more
1 2