实现思路:
- 去除字符串中的干扰项
- 正则匹配(这里需要了解正则知识点)
- 匹配出:
邮政编码
,地址
,身份证号
,手机号
,座机号
,收件人
,收货人
php代码实例说明
- 以下代码是纯php实现,没有依赖数据库,第三方接口等,也不依赖任何扩展类
- 兼容任何php版本
$address = "身份证号:13012519910927226x 收货人吴彦祖收货地址:河北省石家庄市长安区中山东路888号万达广场1001 050000 13211006666";
$address = "河北省石家庄,收货人:吴彦祖;电话:15620209999";
$addressArr = getDetail($address);
echo ''
;
print_r($addressArr);
function getDetail(string $address){
$parse = [];
$parse['name'] = '';
$parse['mobile'] = '';
$parse['postcode'] = '';
$parse['idno'] = '';
$parse['detail'] = '';
$search = ['收货地址', '地址', '收货人', '收件人', '收货', '邮编', '电话', '身份证号码', '身份证号', '身份证', ':', ':', ';', ';', ',', ',', '。', ];
$replace = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '];
$address = str_replace($search, $replace, $address);
$address = preg_replace('/ {2,}/', ' ', $address);
$address = preg_replace('/(\d{3})-(\d{4})-(\d{4})/', '$1$2$3', $address);
preg_match('/\d{18}|\d{17}X/i', $address, $match);
if ($match && $match[0]) {
$parse['idno'] = strtoupper($match[0]);
$address = str_replace($match[0], '', $address);
}
preg_match('/\d{7,11}|\d{3,4}-\d{6,8}/', $address, $match);
if ($match && $match[0]) {
$parse['mobile'] = $match[0];
$address = str_replace($match[0], '', $address);
}
preg_match('/\d{6}/', $address, $match);
if ($match && $match[0]) {
$parse['postcode'] = $match[0];
$address = str_replace($match[0], '', $address);
}
$address = trim(preg_replace('/ {2,}/', ' ', $address));
$split_arr = explode(' ', $address);
if (count($split_arr) > 1) {
$parse['name'] = $split_arr[0];
foreach ($split_arr as $value) {
if (strlen($value) < strlen($parse['name'])) {
$parse['name'] = $value;
}
}
$address = trim(str_replace($parse['name'], '', $address));
}
$parse['detail'] = $address;
return $parse;
}