我有一个必须在用户提供的消息中隐藏电话号码的要求。我已经有一个正则表达式,如下所示:
/\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})/
但这只能识别以下格式的手机号码:
9876543210
我也希望它涵盖以下格式:
987 654 3210
9 8 7 6 5 4 3 2 1 0
(987)654 3210
(987)(654)(3210)
在以上所有格式中,空格都可以用'-'或'。'代替。同样,'('和')'可以替换为'['和']'。
另外,是否可以识别用字符串而不是数字提及的电话号码,例如
九八七六五四有三二一零
数字和字符串的任意组合
编辑:添加我的功能是隐藏联系人号码,如果有的话从内容:
function hide_contact_number($description) {
// Find contact number and hide it!
$regex = "/\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})/";
/*$regex = "/[\([]?([0-9]{3})[\)\]]?[-. ]?[\([]?([0-9]{3})[\)\]]?[-. ]?[\([]?([0-9]{4})[\)\]]?|([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])/";*/
if(preg_match_all($regex, $description, $matches, PREG_OFFSET_CAPTURE)) {
foreach($matches as $matchkey => $match) {
foreach($match as $key => $value) {
$index = 0;
$length = 0;
if(is_array($value)) {
if(is_numeric($value[0]) && strlen($value[0]) >= 10) {
$index = $value[1];
$length = strlen($value[0]);
} else if(strlen($value[1]) >= 10) {
$index = $value[0];
$length = strlen($value[1]);
} else {
// TODO: Do nothing
}
}
if($length > 0) {
// length - 2 => 2 places before end of email id including 1 of index + 1
$description = substr_replace($description, str_repeat("*", $length-2), $index+1, $length-2);
}
}
}
}
return $description;
}
上面的函数不能识别并隐藏我提到的所有数字序列。甚至@CCH的解决方案也无济于事。这个功能有什么问题吗?
这 :
[\([]?([0-9]{3})[\)\]]?[-. ]?[\([]?([0-9]{3})[\)\]]?[-. ]?[\([]?([0-9]{4})[\)\]]?|([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])
将匹配您的所有示例。
演示在这里:https :
//regex101.com/r/h9631Z/4
要获得完整的php功能,请使用此命令:
function hide_contact_number($description) {
$re = '/[\([]?([0-9]{3})[\)\]]?[-. ]?[\([]?([0-9]{3})[\)\]]?[-. ]?[\([]?([0-9]{4})[\)\]]?|([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])[-. ]([0-9])/';
$subst = '*** *** ***';
return preg_replace($re, $subst, $description);
}
您可以更改$ subst来设置它将替换为匹配项的内容。
完整的演示在这里:https : //repl.it/FnSp/3
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句