Robot Woods
Robot Woods

Reputation: 5687

PHP digits to string for preg_match

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/>";
?>

Upvotes: 1

Views: 187

Answers (2)

Mob
Mob

Reputation: 11098

From what you said you want to achieve, I think you'd be better off using is_numeric and strlen, as is_numeric checks whether a variable is a number or a numeric string.

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237847

Try this code:

echo 07307;

You will find, counter-intuitively, that you get the result 3783. This is because numbers starting in 0 are treated as octals, that is, in base 8. So when you cast 07307 to a string, you get "3783". If leading zeros are important, you should be using a string in the first place.

Upvotes: 3

Related Questions