【问题标题】:preg_replace not working!preg_replace 不工作!
【发布时间】:2009-12-26 22:49:48
【问题描述】:

这是我的 Codeigniter 函数:

function edit_phone($phone)
{
            if (preg_match('/^\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/', $phone))
            {
                return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "$1-$2-$3", $phone); 
            }
            else
            {
               $this->CI->validation->set_message('phone', "This must be a 10-digit USA phone number.");
                    return FALSE;       
            }
}

这会验证/检查输入是否正常,但不会在数据库中重新格式化。

验证很棒!但是为什么这不返回一个标准的电话号码呢?!

【问题讨论】:

  • 可能你没有保存edit_phone的返回值?
  • 啊,你可能是对的!你能给我举个例子吗?我是新手……

标签: php codeigniter preg-replace


【解决方案1】:

我认为问题在于它只适用于格式为 1234567890 的数字,但基于 preg_match() 调用中的正则表达式,Kevin 还希望适应以下数字:

  • (123)4567890
  • (123) 456 7890
  • 123-456-7890

如果是这样,preg_replace() 中的正则表达式需要类似于...

preg_replace('/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/', "$1-$2-$3", $phone)

【讨论】:

    【解决方案2】:

    能否给我们提供您尝试填写的示例数据?

    我使用了以下代码:

    $phone = "1234567890";
    echo preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "$1-$2-$3", $phone);
    

    得到:

    123-456-7890
    

    据我所知,这是绝对正确的。

    【讨论】:

    • 我相信迈克尔是正确的。你能告诉我如何获得回报吗?
    • $phone_number = edit_phone("1234567890"); 返回值现在在$phone_number
    猜你喜欢
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多