【问题标题】:modify string if specific regex matches如果特定的正则表达式匹配,则修改字符串
【发布时间】:2016-06-11 07:49:55
【问题描述】:

在 PHP 中工作,我有以下模拟字符串。

"width 40cm height 70cm"

如果字符串不包含冒号并且有一个空格后跟一个数字,我想在那个空格之前添加一个冒号。

我正在寻找的最终结果是:

"width: 40cm height: 70cm"

我尝试了很多使用正则表达式的方法,并在匹配时拆分字符串以添加冒号,但它正在删除匹配字符串。这是我的尝试。

    if(strpos($s, ':') === false) {
        $array = preg_split('/([0-9])/', $s, -1, PREG_SPLIT_NO_EMPTY);
        $array[0] = trim($array[0]) . ':';
        $s = implode('', $array);
    }

【问题讨论】:

    标签: php regex string split


    【解决方案1】:

    我认为这会奏效

    (\w+)(?=\s+\d)
         <------->
         Lookahead to match
         space followed by 
         digits
    

    Regex Demo

    PHP 代码

    $re = "/(\\w+)(?=\\s+\\d)/m"; 
    $str = "width 40cm height 70cm\nwidth: 40cm height 70cm"; 
    
    $result = preg_replace($re, "$1:", $str);
    print_r($result);
    

    Ideone Demo

    【讨论】:

    • 此处无需否定前瞻:(?!:)\s,空格不能是冒号。
    • @CasimiretHippolyte 你是对的..我的错..我在开始时写了前瞻部分,然后添加了\w 部分并将其搞砸了..
    【解决方案2】:

    以下正则表达式可能适合您:

    /(?<!:)(?= \d)/g
    

    有替换::

    $output = preg_replace('/(?<!:)(?= \d)/', ':', $input);
    

    它匹配在空格和数字 (?= \d) 之前且前面没有冒号 (?&lt;!:) 的位置。这就是替换组只能是冒号的原因。

    这称为lookarounds。这里同时使用 positive lookahead (?=...)negative lookbehind: (?&lt;!...)

    https://www.regex101.com/r/oH7cI3/1

    【讨论】:

      【解决方案3】:

      使用环视:

      (?<=[a-z]) # a-z behind
      \          # a space
      (?=\d)     # a digit ahead
      

      查看a demo on regex101.com 并用冒号替换出现的位置。

      【讨论】:

        【解决方案4】:
        $string="width: 40cm height: 70cm";
        

        $temp=exploade(" ",$string);

        foreach($temp as $value){

        if(strstr($value,'width') && strstr($value,'height')){
            $new_temp[]=$value.":";
        }else{
            $new_temp[]=$value;
        }
        

        } $new_string=implode(" ", $new_temp);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-12
          • 2021-10-10
          • 1970-01-01
          • 1970-01-01
          • 2011-09-09
          相关资源
          最近更新 更多