0

I have the following code which places a space in postcode.

(string)$postcode = $row['postcode'];
$first = substr($postcode, strlen($postcode)-3);
$second = substr($postcode, strlen($first));
$postcode = $first . ' ' . $second;

The code works fine for most codes, except some. ie

PN45HA 70448

And i can't understand why? Can anyone shine a light on this?

Thankyou

whistlegull
  • 61
  • 1
  • 1
  • 3

3 Answers3

4

Don't really understand the question, but if it's about the space, this will work:

$postcode = 'PN45HA70448';
$postcode = substr($postcode, 0, -3) . ' ' . substr($postcode, -3);
// PN45HA70 448
Yoshi
  • 54,081
  • 14
  • 89
  • 103
0
$first = substr($postcode, 0, -3);
$second = substr($postcode, -3);
$postcode = $first . ' ' . $second;
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
0
$code = 'PN45HA 70448'
$first = substr($postcode, strlen($postcode)-3); // 448
$second = substr($postcode, strlen($first)); // PN45HA 70
$postcode = $first . ' ' . $second; // PN45HA 70 448

The problem is that not all of your postcodes are simple 6 character postcodes. You're simply adding space before the last 3 characters in whatever string you happen to pass in.

What you may need to do is use a regex:

$code = preg_replace('/([A-Z][0-9][A-Z])\s*([0-9][A-Z][0-9])/', '\1 \2', $code);

This'll take any string which looks like a postcode, with optional spaces between the two halves, and puts in a single space.

Marc B
  • 356,200
  • 43
  • 426
  • 500