简体   繁体   English

仅替换字符串中的所有点,而不替换数字值

[英]Replace all dot only in string, but not in numeric values

I want to replace all occurrence of dot (.) in a string but not a digits or numeric value. 我想替换字符串中所有出现的点(。),而不替换数字或数字值。 I have given example 我举了例子

STRING : 10.10.2015 11.30 09/2007 83 HELLO.HOW.ARE.YOU $.###
OUTPUT : 10.10.2015 11.30 09/2007 83 HELLO HOW ARE YOU $ ###

I tried using preg_replace in php 我尝试在php中使用preg_replace

Use a non-capturing lookbehind group to test if the previous character is a digit or not 使用非捕捉式后向分组来测试前一个字符是否为数字

$string = '10.10.2015 11.30 09/2007 83 HELLO.HOW.ARE.YOU $.###';
$result = preg_replace('/(?<=[^\d])\./', ' ', $string);
var_dump($result);

explanation 说明

(?<=[^\d])\.
 -------- --
     ^    ^
     |    |
     |    ------------------  Escape the `.` so we're working with a literal
     |                          dot rather than "any character"
     |
     -----------------------  Look for any preceding non-digit character
                                but don't include it in the replace group

I am not a preg_replace guru, so I wrote a function, which will split your string to array, then check, if any . 我不是preg_replace专家,所以我编写了一个函数,该函数会将您的字符串拆分为数组,然后检查(如果有) . exist and if it found a dot, it will check, if is the dot located between 2 numbers. 是否存在,如果找到一个点,它将检查该点是否位于2个数字之间。 If it is, my function will replace . 如果是这样,我的函数将替换. with :

function removeDots($string) {
    $arr = str_split($string);
    foreach($arr as $key => $val) {
        if($val == ".") {
            if(!is_numeric($arr[$key-1]) && !is_numeric($arr[$key+1])) {
                $arr[$key] = " ";
            }
        }
    }
    return implode($arr);
}

and here is the result: 结果如下:

$str = "STRING : 10.10.2015 11.30 09/2007 83 HELLO.HOW.ARE.YOU $.###";
echo removeDots($str);

OUTPUT: 输出:

STRING : 10.10.2015 11.30 09/2007 83 HELLO HOW ARE YOU $ ### STRING:2015年10月10日11.30 09/2007 83您好,您好$ ###

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

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