【问题标题】:preg_replace with regex patternpreg_replace 与正则表达式模式
【发布时间】:2015-03-12 05:53:56
【问题描述】:

此代码str_replace('A', ' Amp', $var) 可以将 2.7A 转换为 2.7 Amp

但是,它不应将 A2 转换为 Amp 2

preg_replace 可以用正则表达式解决这个问题吗?

【问题讨论】:

    标签: php regex


    【解决方案1】:

    使用正则后向正则表达式匹配所有在数字之后存在的A

    (?<=\d)A
    

    然后将匹配的A替换为Amp

    DEMO

    echo preg_replace('~(?<=\d)A~', 'Amp', $str);
    

    【讨论】:

    • 它适用于类似的条件。什么是正则表达式模式以使 CR1234A 不转换为 CR1234 Amp?
    • 试试preg_replace('~\.\d+\KA~', 'Amp', $str);
    【解决方案2】:
    $re = "/A\\b/im";
    $str = "2.7A\nA2";
    $subst = "Amp";
    
    $result = preg_replace($re, $subst, $str);
    

    你可以使用这个。\b 不会匹配A2

    【讨论】:

      【解决方案3】:

      试试这个正则表达式 -

      A( |$)
      

      DEMO here

      【讨论】:

        【解决方案4】:
        <?php
        $str="A2";
        $pattren=array();
        $pattren[0]="A2";
        $replacement=array();
        $replacement[0]="amp2";
        echo str_replace($pattren,$replacement,$str);?>
        

        使用正则表达式模式

           <?php
        $str="A2";
        $pattren=array();
        $pattren[0]="/A2/";
        $replacement=array();
        $replacement[0]="amp2";
        echo preg_replace($pattren,$replacement,$str);?>
        

        演示:https://eval.in/299021

        【讨论】:

          【解决方案5】:

          如果您想将 A 更改为 Amp。在任何数字的末尾你都可以试试这个(不是正则表达式)

          $strstr="3.4A"; //any value in this string
          
          
          if ((is_numeric(substr($strstr, 0, strlen($strstr)-1))) && (substr($strstr, -1)=="A")){
              echo str_replace('A', ' Amp', $strstr);
          }
          

          【讨论】:

            猜你喜欢
            • 2017-03-09
            • 2012-09-10
            • 2011-05-20
            • 2016-07-11
            • 2023-04-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多