最近有个项目关于手机靓号及用户搜索想要关键数字的手机号
1. 手机靓号规则匹配 - PHP正则匹配
2. 关键字位搜索 - MYSQL LIKE 使用
靓号规则如下
AAAB、AAA、ABC、ABCD、AABB、ABAB
正则表达式
$exp = [ // 手机靓号正则表达式
'AAAB' => '/([\d])\1{2}/',
'ABCD' => '/(?:(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){3}|(?:9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)|1(?=0)){3})\d/',
'AABB' => '/(\d)\1(\d)\2/',
'ABAB' => '/(\d)(\d)\1\2/',
'ABC' => '/(?:(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){2}|(?:9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)|1(?=0)){2})\d/'
];
$phone = '138XXXXXXXX';
// 主要为了匹配关键数字最大价格
$priceArr = ['000' => 98, '111' => 98, '222' => 98, '333' => 98, '444' => 98, '555' => 188, '666' => 288, '777' => 188, '888' => 288, '999' => 188];
foreach ($exp as $key => $value) { // 循环匹配
preg_match_all($value, $phone, $arr); // 匹配全部关键数字
if(count($arr[0])){
$pKey = $arr[0][0];
if($key === 'AAAB'){
foreach ($arr[0] as $val) { // 找出价格最高的关键数字 靓号类型
if($price < $priceArr[$val]){
$price = $priceArr[$val];
$pKey = $val;
}
}
if(substr($phone, -3) === $pKey){
$key = 'AAA';
}
}else{
$price = $default;
}
$type = $key;
break;
}else{
$price = $default;
}
}
$rep = '<span class="peach">'.$pKey.'</span>'; // 前端显示的需要
$phone_tmp = preg_replace('~'.$pKey.'~', $rep, $phone, 1); // 正则替换
$price ;; // 该号码价格
$type ;; // 号码的类型
//
//
用户搜索想要关键数字位置的号码 - 关键数字高亮
在mysql like 中 `_` 表示一个字符的搜索
所以前端把form input 全部提交后,把null 全替换成 _
如上图这般 替换后变成
// 对应代码
$number;; // 前端提交的号码数组
$notNullNumber = array_filter($number, function ($var){ // 过滤空的位置,得到有数字对的key=>value 数组
return $var === '' ? false : true;
}); // [2=>5, 4=>1, 5=>0, 6=>1, 9=>8]
$keyNumber = array_keys($notNullNumber); // 主要为了把这些位置的数字 高亮
foreach ($number as &$value) {
if($value === '') $value = '_';
}
$number = implode("", $number);
// $number = '__5_101__8_'; // 得到匹配后的号码
// 所以在mysql 中查询sql;
// $sql = "select * form t_phone where phone like {$number}";
// 查询出来的结果 进行号码高亮
function phoneFormat($phone, $format = [3,4,5,6]){// $phone查出来号码 、 $format对应位置需要高亮
$phone = str_split($phone);
foreach ($format as $value) {
$phone[$value] = "<text>".$phone[$value]."</text>";
}
return implode('', $phone);
}
方法调用 : phoneFormat($phone, $keyNumber);
//
更多原创博客 - blog.cym0.com
大神们,勿喷