preg_match 邮政编码和州无效
preg_match zip code & state not working
不确定为什么下面找不到 zip 和状态?
$str = 'contact_widget_statezip">NM 87035 ';
$pattern = '[A-Z]{2}\W{1,10}[0-9]{5}';
preg_match_all($pattern, $str, $amatches);
谢谢
格伦
试一试,
<?php
$str = 'contact_widget_statezip">NM 87035 ';
$pattern = '~([A-Z]{2})\s*([0-9]){5}~';
preg_match_all($pattern, html_entity_decode($str), $amatches);
print_r($amatches);
输出:
Array
(
[0] => Array
(
[0] => NM? 87035
)
[1] => Array
(
[0] => NM
)
[2] => Array
(
[0] => 87035
)
)
这会将您的字符串 NM 87035
转换为 NM 87035
,因为
= </code>。然后搜索两个大写字母、任意数量的白色 space,然后搜索 5 个数字。如果您需要白色space 将<code>*
更改为+
..
更新...
\W{1,10}
在您的示例中不起作用,因为 \W
是 \w
的倒数,后者是任何单词字符。符号、分号和白色 space 属于该组,但 nbsp
不属于。如果你不想解码实体而只是忽略白色 space 你可以使用 [A-Z]{2}[[a-zA-Z0-9; &]{1,10}[0-9]{5}
然后对于 PHP 它会是......
<?php
$str = 'contact_widget_statezip">NM 87035 ';
$pattern = '~([A-Z]{2})[a-zA-Z0-9; &]{1,10}([0-9]{5})~';
preg_match_all($pattern, $str, $amatches);
print_r($amatches);
谢谢克里斯,
您的意见有助于此解决方案。
下面找到一个邮政编码和州并忽略中间没有 html_entity_decode
.
的垃圾
$str = 'contact_widget_statezip">NM 87035 ';
$pattern = "\b[A-Z]{2}\b.{1,10}\b[0-9]{5}\b/s";
不确定为什么下面找不到 zip 和状态?
$str = 'contact_widget_statezip">NM 87035 ';
$pattern = '[A-Z]{2}\W{1,10}[0-9]{5}';
preg_match_all($pattern, $str, $amatches);
谢谢 格伦
试一试,
<?php
$str = 'contact_widget_statezip">NM 87035 ';
$pattern = '~([A-Z]{2})\s*([0-9]){5}~';
preg_match_all($pattern, html_entity_decode($str), $amatches);
print_r($amatches);
输出:
Array
(
[0] => Array
(
[0] => NM? 87035
)
[1] => Array
(
[0] => NM
)
[2] => Array
(
[0] => 87035
)
)
这会将您的字符串 NM 87035
转换为 NM 87035
,因为
= </code>。然后搜索两个大写字母、任意数量的白色 space,然后搜索 5 个数字。如果您需要白色space 将<code>*
更改为+
..
更新...
\W{1,10}
在您的示例中不起作用,因为 \W
是 \w
的倒数,后者是任何单词字符。符号、分号和白色 space 属于该组,但 nbsp
不属于。如果你不想解码实体而只是忽略白色 space 你可以使用 [A-Z]{2}[[a-zA-Z0-9; &]{1,10}[0-9]{5}
然后对于 PHP 它会是......
<?php
$str = 'contact_widget_statezip">NM 87035 ';
$pattern = '~([A-Z]{2})[a-zA-Z0-9; &]{1,10}([0-9]{5})~';
preg_match_all($pattern, $str, $amatches);
print_r($amatches);
谢谢克里斯,
您的意见有助于此解决方案。
下面找到一个邮政编码和州并忽略中间没有 html_entity_decode
.
$str = 'contact_widget_statezip">NM 87035 ';
$pattern = "\b[A-Z]{2}\b.{1,10}\b[0-9]{5}\b/s";