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

时间:2016-03-17 10:59:20

标签: php

我想替换字符串中所有出现的点(。)而不是数字或数值。我举了个例子

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 $ ###

我尝试在php中使用preg_replace

2 个答案:

答案 0 :(得分:2)

使用非捕获的lookbehind组来测试前一个字符是否为数字

select id, name, type, region,
       max(seqnum = 1 then date_hired end) as date_hired1,
       max(seqnum = 2 then date_hired end) as date_hired2,
       max(seqnum = 3 then date_hired end) as date_hired3,
       max(seqnum = 4 then date_hired end) as date_hired4
from (select t.*,
             row_number() over (partition by id order by date_hired) as seqnum
      from t
     ) t
group by id, name, type, region;

解释

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

答案 1 :(得分:0)

我不是preg_replace大师,所以我写了一个函数,它将你的字符串拆分为数组,然后检查,如果存在任何.,如果找到一个点,它将检查,如果是点位于两个数字之间。如果是,我的功能会将.替换为

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);
}

以下是结果:

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

<强>输出:

     

STRING:10.10.2015 11.30 09/2007 83你好如何$ ###