Regular Expressions 101

Community Patterns

Your search did not match anything

Community Library Entry

1

Regular Expression
PCRE2 (PHP >=7.3)

/
(?:\G|(LETTER))A
/
gm

Description

$input = "I am the letter LETTERAAAAAAAAAA like AAAlpha AAAAnd I will always be the first in LETTERAAAAAlphabet.";
$output = preg_replace('/(?:\G|(LETTER))A/', '$1B', $input);
echo $output;

Expected output:

I am the letter LETTERBBBBBBBBBB like AAAlpha AAAAnd I will always be the first in LETTERBBBBAlphabet.

Explanation:

  • The \G ensures all consecutive 'A's are matched only if they are part of a previous match.
  • The (LETTER) ensures that "LETTER" is not lost in the replacement.
  • Each 'A' is individually substituted with 'B' while keeping the exact same length.
Submitted by Davd Blanchard - a month ago