繁体   English   中英

Preg替换除+之外的所有非数字字符

[英]Preg Replace all non numerical characters except +

我想替换除+之外的字符串中的所有非数字字符。

我试过这个问题,但它不起作用......

这就是我现在所拥有的:

$nn = preg_replace("/([^0-9\/+]+)/", "", $string );

它可以100%工作,除了以任何方式移除+ ...

编辑

我的输入将始终只包含1 +,如果有更多,则应删除它们。

基本上,如果用户输入的电话号码为(015) 234-2634 ,则应返回为+27152342634 (南非国家代码 - 我稍后会添加+27)但是如果+27 (15) 234-2634是输入, +27152342634应该返回。

您应该可以使用以下正则表达式执行此操作:

[^0-9+]

preg_replace()

$nn = preg_replace('/[^0-9+]/', '', $string);

您当前的正则表达式也保持正斜杠,以便保持该功能:

$nn = preg_replace('/[^0-9\/+]/', '', $string);

带输出的示例代码:

<?php
$string = '+27 (15) 234-2634';
$nn = preg_replace("/[^0-9+]/", "", $string );
echo $nn . "\n";
?>

结果是:

+27152342634

更新 (仅保留第一个匹配+
根据您最新的问题更新,您还只想保留找到的第一个 +符号。 为此,由于可能没有关于第一个符号位置的“规则”(例如“它必须是字符串中的第一个字符),我建议使用除preg_replace()以外的其他方法:

$nn = preg_replace("/[^0-9+]/", "", $string);
if (substr_count($nn, '+') > 1) {
    $firstPlus = strpos($nn, '+') + 1;
    $nn = substr($nn, 0, $firstPlus) . str_replace('+', '', substr($nn, $firstPlus));
}

此代码将正常执行原始preg_replace() ,然后,如果结果中有多个+符号,它将获得结果的子字符串,直到第一个+ ,然后执行字符串替换以替换所有剩余的+符号。 你也总是可以在这里使用第二个preg_replace() ,但是只删除一个+符号就会有点过分。

这是示例的键盘输入。

因此,如果你想删除所有的加号和非数字,除了第一个+之外你需要一个断言:

$str = preg_replace('~  (?! ^ \+)  [^\d]  ~x', "", $str);

请注意,我在这里使用了不同的分隔符~ x模式用于正则表达式中的额外空格。

这只有在+实际上是字符串中的第一个字符时才有效。 在它之前是否有空间,两者都将被废弃。

正如我理解你的问题,你可以使用preg_replace_callback( http://php.net/manual/en/function.preg-replace-callback.php )函数来实现这个目标。

脚步:

  1. 使用括号获取3位数并删除括号并前导0
  2. 删除所有非数字字符(包括+)
  3. 如果它有国家代码只需在开头添加“+”
  4. 如果没有将“+”country_code添加到开头

//$string = '(015) 234-2634';
$string = '+27 (015) 234-2634';
//  \(\d{3}\)\s* to capture (015)
//  \D to capture all non numeric characters
//  ^\d{2} to capture first two digits
$pattern = array("/\(\d{3}\)\s*/","/\D/","/^\d{2}/");

echo preg_replace_callback($pattern, function($matches){
    $countrycode = 27;

    if(strlen($matches[0])>4){ //(015)
        return substr($matches[0],2,-1); //grab 15 from (015)
    }
    else if(is_numeric($matches[0]) && $matches[0]==$countrycode ){
                //if it has country code just add "+" to the begining
        return "+".$matches[0];
    }
    else if(is_numeric($matches[0]) && $matches[0]!=$countrycode ){
                //if it has not country code add "+" and countrycode to the begining
        return "+".$countrycode.$matches[0];
    }
   else{
       // if its not a digit return null
       return null; 
   }
}, $string);

请注意我不是一个正则表达式专家,它可能有简单的方法来完成你的任务,但这个例子对我来说很完美。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM