【问题标题】:Why does this PHP statement strip 7's unexpectedly?为什么这个 PHP 语句会意外删除 7?
【发布时间】:2013-03-07 16:38:47
【问题描述】:

我希望有一双新的眼睛来看待我的问题,这让我发疯。任何帮助将不胜感激。

如果用户在电话号码的开头输入第一个“44”,我将尝试从 2 行 PHP 代码中去除:

    $telephone = '44789562356';
    $telephone = str_replace(' ','',$telephone);
    $telephone = str_replace('+44','0',$telephone);
if(strpos($telephone,"44")==0){
        $telephone = substr($telephone,2);
        $telephone = '0'.$telephone;
    }

为什么它会从所有电话号码中去掉“7”?

【问题讨论】:

  • 好吧,首先,您的strpos 检查应该使用=== 而不是==(如果44 没有出现在电话号码中,则if 语句中的代码将运行完全)。
  • 除了评论和回答。它已经工作正常了。 codepad.org/ai61PShL
  • 它不会为我剥离 7。当我运行它时,我得到0789562356
  • 如果输入为 '+44789562356',则 7 将被删除,因为 Colin Morelli 提出了这一点。
  • 不,如果它没有找到任何东西,它会返回false。还有false == 0,但不是false === 0

标签: php substr strpos


【解决方案1】:

就像 Colin 评论的那样,您需要在从 strpos() 返回时使用严格的比较 ===,因为如果找不到子字符串,它会返回 false,如果它位于字符串的开头,则返回 0 并且false == 0 为真,false === 0 为假。

或者,您可以使用正则表达式来指定仅在字符串开头进行匹配,如下所示:

if( preg_match('/^44/', $telephone) ) { ... }

或者用它替换:

preg_replace('/^44/', '0', $telephone);

您的代码可以简化为:

$telephone = '+44-789 56-2356 ask for larry';
$telephone = preg_replace('/[^0-9]/','',$telephone); // remove all non-numeric characters
$telephone = preg_replace('/^44/','0',$telephone);
echo $telephone;
// output: 0789562356

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 2021-12-25
    • 2014-03-30
    • 1970-01-01
    相关资源
    最近更新 更多