I hate this code. What it does is take zipcode from html pages are verifies if the zipcode is USA or Canada.
<?php
$contents = file_get_contents('853755.html');
preg_match_all('/<td id="u_zipCode">(.*?)<\/td>/s', $contents, $matches);
$data = implode("|",$matches[0]);
$string = str_replace(' ', '', $data);
if(preg_match('/^[1-9][0-9]*$/',$string)){
echo "Canada";
}
else
{
echo "USA";
}
?>
I tried very had to search solution for it. But i can't find the solution. I even tried the regex that it should only contain Numbers not a single alphabet. But this doesn't seem to work in any way. The zipcode are given in this format,
USA: 97365
USA: 97365-97366
Canada: j8n7s1
Canada: N2L5Y6
Kindly help me with this solution. Thanks
Since there can only be one element with a particular ID, you don't need to use preg_match_all()
, you can use preg_match()
.
preg_match('/<td id="u_zipCode">(.*?)<\/td>/s', $contents, $match);
Then you don't need to use implode()
. The part that matches the capture group will be in element 1 of the match
array.
$string = str_replace(' ', '', $match[1]);
if(preg_match('/^\d{5}(-\d{4})?$/',$string)) {
echo "USA";
} else {
echo "Canada";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.