代码之家  ›  专栏  ›  技术社区  ›  ZeroGravity

查找字符串中的第一个“无效”字符(清除电话号码)

  •  1
  • ZeroGravity  · 技术社区  · 8 年前

    我们并不过分担心生成的电话号码的确切格式。当用户更新他们的个人资料时,他们可能会被强制清理。数字为美国格式。

    举几个例子。我想可能还有其他变化:

    "(123) 456-7890 Betty's cell"
    becomes
    "(123) 456-7890" and "Betty's cell"
    
    "123-456-7890  Betty's cell
    becomes
    "123-456-7890" and "Betty's cell"
    
    "456-7890  Betty's cell
    becomes
    "456-7890" and "Betty's cell"
    
    "456-7890 ext. 123  Betty's cell
    becomes
    "456-7890 ext. 123" and "Betty's cell"
    

    有效的电话号码字符为 "+()-0123456789 " "ext." 我可以清理现有数据,使所有外部变量都相同。我们很乐意找到字符串中第一个“无效”字符的位置并将其拆分。

    一直在搜索,但似乎找不到任何适合这种情况的东西。感谢您的建议。

    2 回复  |  直到 8 年前
        1
  •  2
  •   Dr. X    8 年前

    ^([\+\(\)\-0-9 ]*)([A-Za-z' ]*)$
    

    Group1 result总是number,Group2 result将是名称和姓氏 你可以查一下 https://regex101.com/r/PhEQNH/1/

    $re = '/^([\+\(\)\-0-9 ]*)([A-Za-z\' ]*)$/';
    $str = '123-456-7890  Betty\'s cell
    ';
    
    preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
    
    // Print the entire match result
    var_dump($matches);
    
        2
  •  1
  •   trincot    8 年前

    preg_match :

    function splitPhoneNotes($s) {
        preg_match("~^([\d() +-]+(?:ext\.[\d() -]+)?)(.*)~", $s, $res);
        return [
            "phone" => trim($res[1]),
            "note" => trim($res[2]) 
        ];
    }
    
    // Sample inputs
    $arr = [
        "(123) 456-7890 Betty's cell",
        "123-456-7890  Betty's cell",
        "456-7890  Betty's cell",
        "+1 (324) 456-7890 ext. 33 Betty's cell",
    ];
    
    // Apply the function to each of the inputs
    $res = array_map('splitPhoneNotes', $arr);
    
    // Results
    print_r($res);
    

    看它运行 repl.it