I have a requirement where I have to hide phone number in messages provided by users. I already have one regular expression which is as follows:
/\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})/
But this can only identify mobile numbers of following formats:
9876543210
I want it to cover following formats too:
987 654 3210
9 8 7 6 5 4 3 2 1 0
(987) 654 3210
(987) (654) (3210)
In all the above formats, spaces can be replaced by either '-' or '.'. Also, '(' and ')' can be replaced by '[' and ']'.
Also, is it possible to identify phone numbers which are mentioned with strings instead of digits, like
Nine eight seven six five four three two one zero
Any combination of digits and strings
EDIT: Adding my function which is hiding contact numbers if any from content:
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;
}
The above function does not identify and hide all the number sequences I have mentioned. Even @CCH's solution does not help. Is anything wrong with this function?