preg_replace掩盖电话号码的一部分 [英] preg_replace to mask parts of a phone number
问题描述
好吧,在重新阅读我以前的帖子以寻求帮助时,我发现我并没有明确说明我正在尝试做什么,也没有指出原因.我有一个我正在忙于开发的网站,它可能会显示人们留下电话号码的消息(即使这很愚蠢),我需要负责并确保在这种情况下号码被屏蔽.首先,我需要搜索存储在变量 $messagetext 中的消息文本,然后我需要使用 preg_replace() 函数来屏蔽部分数字,因此不清楚数字是什么,所以如果有人要留言和他们的号码是"07921234567",它将在邮件中显示为"07 ** 12 * 45 **".怎么办呢?我只想找出要用于搜索可能以+44或07开头的整数(英国号码)的函数,以及preg_replace()函数中的正则表达式是什么:
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!
任何事情都值得赞赏!
推荐答案
我认为您要查找的正则表达式是这样的:
I think the regex you are looking for is this:
(00447|\+?447|07)([0-9]{9})
要屏蔽电话号码,您需要使用 preg_replace_callback()
,像这样:
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);
您可以在演示中看到它的运行.例如,输入 07921234567
会产生 07 ** 12 * 45 **
作为输出.
You can see it working in the demo. For example, an input of 07921234567
yields 07**12*45**
as output.
这篇关于preg_replace掩盖电话号码的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!