【问题标题】:preg_replace to mask parts of a phone numberpreg_replace 屏蔽部分电话号码
【发布时间】:2012-07-24 00:05:02
【问题描述】:

好的,所以在重新阅读了我之前寻求帮助的帖子后,我发现我并没有完全清楚我要做什么,也没有指出原因。我有一个我正在忙于开发的网站,它可能会显示人们留下电话号码的消息(即使这很愚蠢),我需要负责并确保在这种情况下数字被屏蔽。首先,我需要搜索存储在变量 $messagetext 中的消息文本,然后我需要使用 preg_replace() 函数来屏蔽部分数字,因此不清楚数字是什么,所以如果有人要留言和他们的号码是“07921234567”,它会在消息中显示为“07**12*45**”。这将如何完成?我只想找出我将使用什么函数来搜索可能以 +44 或 07 开头的整个数字(英国号码),以及 preg_replace() 函数中的 REGEX,就像我所拥有的一样:

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

所有这些都是替换整个数字。我不想这样做的原因是我还有另一个网站正在处理社交网络隐私问题,我需要屏蔽我为我的示例检索到的部分电话号码。

希望这更清楚,如果有人可以帮助我提供一些很棒的代码!

任何事情都值得赞赏!

【问题讨论】:

  • 如果用户将他们的号码更改为 Zero792One234Five67?
  • @MarcB:我认为他正试图尽其所能掩盖数字,但如果用户试图绕过过滤器,那么可能没有办法。
  • 为什么不用*s 替换最后 9 位数字?那么它将永远是07*********+447*********447*********

标签: php regex masking


【解决方案1】:

我认为您正在寻找的正则表达式是这样的:

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

要屏蔽电话号码,您需要使用preg_replace_callback() 进行自定义回调,如下所示:

$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);

你可以看到它在the demo 中工作。例如,07921234567 的输入产生07**12*45** 作为输出。

【讨论】:

  • 我会将第一组写为(00447|\+?447|07),以考虑英国手机号码的所有可能合法表达
  • @Dave - 感谢您的提示 - 我将您修改后的正则表达式添加到代码中。我还创建了一个新的演示。
【解决方案2】:

我不确定有效的英国电话号码中有多少个号码。假设有 11 个数字:

preg_replace(/(\d{2})\d{2}(\d{2})\d(\d{2})\d{2}/, "$1**$2*$3**");

这并不是一个很好的解决方案,因为我猜测可能会有不同长度的电话号码,人们可以在号码中放置空格以达到视觉目的。

【讨论】:

    【解决方案3】:
    <?PHP
    function maskTelephoneNumber($phonenumber, $trim, $maskCharacter)
    {
    $suffixNumber = substr($phonenumber, strlen($phonenumber)-$trim,$trim); 
    $prefixNumber = substr($phonenumber, 0, -$trim); 
    
    for ($x = 0; $x < strlen($prefixNumber); $x++):
        $str.= ( is_numeric($prefixNumber[$x]) )? str_replace($prefixNumber[$x], $maskCharacter, $prefixNumber[$x]) : $prefixNumber[$x];
    endfor;
    
    return  $str.$suffixNumber;     
    }
    
    $trim = 4;
    $maskCharacter='*';
    $phonenumber = '555-666-7777';
    
    echo maskTelephoneNumber($phonenumber,$trim, $maskCharacter);
    

    【讨论】:

      猜你喜欢
      • 2018-05-04
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      相关资源
      最近更新 更多