iKnowNothing
iKnowNothing

Reputation: 175

Replace only single letters and not letters which occur in pairs using PHP Regex

This is the input string:

BQ^2*Z*(2*Y + Z) == AP^2*Y^2 - PQ^2*Y^2

This is the desired output:

BQ^2*$z*(2*$y + $z) == AP^2*$y^2 - PQ^2*$y^2

I tried using the following regex:

([A-Z])(?![A-Z])

However, it only leaves the first character out of the replacement. The current result is:

B$1^2*$1*(2*$1 + $1) == A$1^2*$1^2 - P$1^2*$1^2

How should I change the above regex to get the right output.

Upvotes: 0

Views: 31

Answers (2)

Toto
Toto

Reputation: 91518

If you want to lowercase your variable names, use preg_replace_callback:

$input = 'BQ^2*Z*(2*Y + Z) == AP^2*Y^2 - PQ^2*Y^2';

$output = preg_replace_callback(
            '/(?<![A-Z])[A-Z](?![A-Z])/',
            function ($m) {
                return '$' . strtolower($m[0]);
            },
            $input);
print_r($output);

Output:

BQ^2*$z*(2*$y + $z) == AP^2*$y^2 - PQ^2*$y^2

Upvotes: 0

anubhava
anubhava

Reputation: 785886

You can use lookaround regex:

$repl = preg_replace('/(?<![A-Z])[A-Z](?![A-Z])/', '$$0', $str);
//=> BQ^2*$Z*(2*$Y + $Z) == AP^2*$Y^2 - PQ^2*$Y^2

RegEx Demo

RegEx Explanation:

  • (?<![A-Z]): Lookbehind to assert that we don't have an uppercase letter at previous position
  • [A-Z]: Match an uppercase letter
  • (?![A-Z]): Lookahead to assert that we don't have an uppercase letter at next position

Additional note:

For your given input following regex will also work:

\b[A-Z]\b

But will miss matching Y in input: PQ^2*5Y^2

Upvotes: 2

Related Questions