【问题标题】:Regex to find and expression and insert into the middle正则表达式查找和表达并插入到中间
【发布时间】:2021-03-21 19:00:09
【问题描述】:

我会尽量简短。我正在尝试使用 preg_replace 的正则表达式来查找数字,但我想非破坏性地编辑字符串。

一个例子:(尽管由于数据保护,这是一个近似值)

$subject_string = 'section 1.1: Disability ........' ;
$outcome = preg_replace( '/$section[\d.\d]+/' ,  '\<hr/\>'  , $subject_string );
// $outcome will be: "\<hr/\>section 1.1: Disability ........"

任何帮助将不胜感激

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

    使用

    \bsection\s*\d+(?:\.\d+)*:
    

    替换为&lt;hr/&gt;$0。见regex proof

    解释

    --------------------------------------------------------------------------------
      \b                       the boundary between a word char (\w) and
                               something that is not a word char
    --------------------------------------------------------------------------------
      section                  'section'
    --------------------------------------------------------------------------------
      \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                               more times (matching the most amount
                               possible))
    --------------------------------------------------------------------------------
      \d+                      digits (0-9) (1 or more times (matching
                               the most amount possible))
    --------------------------------------------------------------------------------
      (?:                      group, but do not capture (0 or more times
                               (matching the most amount possible)):
    --------------------------------------------------------------------------------
        \.                       '.'
    --------------------------------------------------------------------------------
        \d+                      digits (0-9) (1 or more times (matching
                                 the most amount possible))
    --------------------------------------------------------------------------------
      )*                       end of grouping
    --------------------------------------------------------------------------------
      :                        ':'
    

    代码 sn-p

    $re = '/\bsection\s*\d+(?:\.\d+)*:/';
    $str = 'section 1.1: Disability ........';
    $subst = '<hr/>$0';
    $result = preg_replace($re, $subst, $str);
    echo "The result of the substitution is ".$result;
    

    【讨论】:

    • 这太棒了,优雅!谢谢!理解正则表达式还有很长的路要走。在这里,捕获和反向引用是我缺少的关键!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多