I have a script that requires the postcode input to have a space in it, if not it will fail. Straight forward, but UK postcodes can have gaps in different places, i.e W1 4SB, NW2 6PT or SG14 1LB how would I change users input, if there is no gap entered to the correct format using PHP?
A:
If it's always in the same place (based on your examples), you could do this:
<?php
//...assuming postalcode has already been loaded into $postalcode...
//If the fourth-to-last char isn't a space, add one in that position
if (substr($postalcode, -4, 1) != " ") {
$postalcode = substr($postalcode, 0, strlen($postalcode) - 3) +
" " + substr($postalcode, -3);
}
//do whatever with $postalcode you'd normally do...
?>
Probably want to do some more checking around that, like it is a min length, etc. But that should get you going.
Parrots
2009-06-18 14:57:57
+3
A:
Postcodes always end with digit-letter-letter. Simply look for a space at the 4th character before the end of the string and if it's not there, insert it.
Jon Grant
2009-06-18 15:01:55
A:
The space is actually always at the same position for fully qualified UK Postcodes. It is just before the last 3 digit/letters
So first validate that it is a real UK postcode and it matches the format, then do this:
$postcode = 'E154EZ';
if( isValidPostcode($postcode) ){
$postcode = str_replace(' ','',$postcode);
$postcode = wordwrap($postcode, strlen($postcode)-3,' ', true);
}
PS. You can get the UK Postcode validation regexes + extra info from here
duckyflip
2009-06-18 15:11:57
isValidPostcode - is that PEAR?
2009-06-18 15:26:08
It's just a dummy function I placed to indicate where you should validate the postcode. you can actually implement the function just by using the regex in the link I posted.
duckyflip
2009-06-18 17:20:17
A:
The solution that worked is:
$postcode = trim(strip_tags($_REQUEST['postcode']));
$test = $postcode;
if(substr($test, -3) == " ") {
$postcode = $postcode;
}
else {
function stringrpl($x,$r,$str)
{
$out = "";
$temp = substr($str,$x);
$out = substr_replace($str,"$r",$x);
$out .= $temp;
return $out;
}
$test = stringrpl(-3," ",$test);
$postcode = $test;
}