Search code examples
phpregexmasking

preg_replace to mask parts of a phone number


Ok so after having re-read over my previous post asking for help on this one I found I wasn't making it exactly clear what I was trying to do nor was I pointing out why. I have a site that I'm busy developing which may possibly display messages where people have left their phone numbers (even though this is stupid) and I need to be responsible and make sure should this be the case the numbers are masked. Firstly I need to search through the message text which is stored in a variable $messagetext then I need to use the preg_replace() function to mask parts of the number so its not clear what the number is so if someone were to leave a message and their number was "07921234567" it would appear on the message as "07**12*45**". How would this be done ? All I would like is to find out what function I'd use to search for the entire number (United Kingdom number) which may start +44 or 07 and what REGEX in the preg_replace() function as all i had was:

$extractednum = preg_replace( "/[0-9]/","*",$extractednum);
echo ($extractednum);

All this does is replace the entire number. The reason why I don't wanna do this is I also have another site I'm working on to do with social networking privacy and I need to mask parts of the telephone numbers I retrieve for my example.

Hopefully this is more clear and if someone could help me out with some code that would be great!

Anything is appreciated!


Solution

  • I think the regex you are looking for is this:

    (00447|\+?447|07)([0-9]{9})
    

    To mask the phone numbers, you'll need a custom callback with preg_replace_callback(), like this:

    $extractednum = preg_replace_callback( "/(00447|\+?447|07)([0-9]{9})/", function( $matches) {
        // This will return the number unmodified
        // return $matches[1] . $matches[2]; 
        // Instead, set whichever characters you want to be "*" like this:
        $matches[2][0] = $matches[2][1] = $matches[2][4] = $matches[2][7] = $matches[2][8] = "*";
        return $matches[1] . $matches[2]; 
    } , $extractednum);
    

    You can see it working in the demo. For example, an input of 07921234567 yields 07**12*45** as output.