正则表达式php解析邮政编码并从字符串中删除
我有一个解析地址的应用程序,一直在尝试实现下面的正则表达式来从地址中获取美国邮政编码。一旦我抓取了它,我想从地址字符串中删除邮政编码,因为zipcode会干扰抓取电话号码。但是,下面的代码并没有抓取zipcode正则表达式php解析邮政编码并从字符串中删除,php,regex,zipcode,Php,Regex,Zipcode,我有一个解析地址的应用程序,一直在尝试实现下面的正则表达式来从地址中获取美国邮政编码。一旦我抓取了它,我想从地址字符串中删除邮政编码,因为zipcode会干扰抓取电话号码。但是,下面的代码并没有抓取zipcode $string = "John Doe 1234 Main Street Peoria, IL 60601 (555) 555-5555"; function extract_zipcode_from($string){ preg_match_all("/\b[A-Z]{2}\s+
$string = "John Doe 1234 Main Street Peoria, IL 60601 (555) 555-5555";
function extract_zipcode_from($string){
preg_match_all("/\b[A-Z]{2}\s+\d{5}(-\d{4})?\b/", $string, $matches);
return $matches[0];
}
$zip = extract_zipcode_from($string);
$zip = print_r(implode("\n", $zip),true);
$string = str_ireplace($zip,"",$string);
有人能建议如何让它工作吗
谢谢 试试这段代码,它将为您提供手机和拉链,而无需更换任何东西 假设Zip和phone始终位于字符串的末尾,则Zip之后的任何内容都是电话号码。
$string = "John Doe 1234 Main Street Peoria, IL 60601 (555) 555-5555";
preg_match("/(?P<zip>\d{5})(?P<phone>.*)$/",$string,$match);
echo "Zip : ".$match['zip'];
echo "<br>";
echo "Phone : ".$match['phone'];
$string=“伊利诺伊州皮奥里亚大街1234号约翰·多伊60601(555)555-5555”;
preg_match(“/(?P\d{5})(?P.*)$/”,$string,$match);
echo“Zip:.$match['Zip'];
回声“
”;
echo“Phone:.$match['Phone'];
为什么不使用preg\u replace()
将其删除。不需要手动搜索和str_替换。代码中的错误是没有将邮政编码包装在括号中以捕获它们(\d{5}(\d{4})
-一旦得到该值,请查看matches数组中的内容。然后,在磨练了正则表达式之后,按照mario的建议使用preg_replace()。您的意思是preg_match_all(“/\b[A-Z]{2}\s+(\d{5})(\d{4})\b/”,$string,$matches);我能够在另一个网站上找到我的追随者来工作。不知道为什么pregreplace比Stru_replace好。从我读到的str_ireplace非常快:$zip_pattern=“/\d{5}/”$str=“Mission Viejo,加利福尼亚州92692”;preg_匹配($zip_模式,$str,$regs)$zip=$regs[0]$str=str_ireplace($zip,“,$str);