Thanks in advance, I feel like I’m overlooking something very simple. I have some numerical zip codes that I need to run through a function…however, I need to validate that the input is a five digit string. But, no matter how I try to cast the number to string, it’s failing. Is there some other way I should be encoding or formatting?:
<?php
$code=07307;
$wrapped_code='07307';
$castcode=(string)$code;
$strcode=''.$code;
echo (preg_match('/^\d{5}$/', $code))?'success with code<br/>':'code failed, saw:'.$code."<br/>";
echo (preg_match('/^\d{5}$/', $wrapped_code))?'success with wrapped_code<br/>':'wrapped_code failed, saw:'.$wrapped_code."<br/>";
echo (preg_match('/^\d{5}$/', $castcode))?'success with castcode<br/>':'castcode failed, saw:'.$castcode."<br/>";
echo (preg_match('/^\d{5}$/', $strcode))?'success with strcode<br/>':'strcode failed, saw:'.$strcode."<br/>";
?>
Try this code:
You will find, counter-intuitively, that you get the result
3783. This is because numbers starting in0are treated as octals, that is, in base 8. So when you cast07307to a string, you get"3783". If leading zeros are important, you should be using a string in the first place.