Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find and expression and insert into the middle

I'll be brief as I can. I'm trying to use preg_replace's regex to find a digit, but I want to non destructively edit the string.

an example: (albeit this is an approximation due to data protection)

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

Any help would be gratefully received

like image 623
new_user_one Avatar asked Dec 20 '25 09:12

new_user_one


1 Answers

Use

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

Replace with <hr/>$0. See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  \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
--------------------------------------------------------------------------------
  :                        ':'

Code snippet:

$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;
like image 120
Ryszard Czech Avatar answered Dec 21 '25 23:12

Ryszard Czech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!