正则表达式查找和表达并插入到中间

Regex to find and expression and insert into the middle

我会尽量简短。我正在尝试使用 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 ........"

如有任何帮助,我们将不胜感激

使用

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

替换为<hr/>[=13=]。参见 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
--------------------------------------------------------------------------------
  :                        ':'

代码片段:

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