Search code examples
phpregexreplacepositive-lookbehind

Replace letter "A" if preceded by a digit


This code str_replace('A', ' Amp', $var) can convert 2.7A to 2.7 Amp.

But, it should not convert A2 to Amp 2.

Can preg_replace() with a regex pattern solve this issue?


Solution

  • Use a positive lookbehind beased regex to match all the A's which exists just after to a digit.

    (?<=\d)A
    

    Then replace the matched A with Amp.

    DEMO

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