bhaskarc
bhaskarc

Reputation: 9541

Conditional Regex Replace

Consider the following regex rule for text replacement

$mystring = preg_replace('/'.$myitem.'[ab]/', "", $mystring);

This will replace $myitem with a blank character in $mystring if and only if it is followed by either a or b.

My requirement is not to replace it with a blank character but to replace it with:

a if a is encountered or b if b is encountered.

I cannot do it in two iterations like:

$mystring = preg_replace('/'.$myitem.'a/', "a", $mystring);
$mystring = preg_replace('/'.$myitem.'b/', "b", $mystring);

because the first iteration will also have some side effects on $mystring making the second rule useless in that case.

Is there a way to do this conditional replacement in a single iteration ?

edited in response to answers

OK I had oversimplified my question but here is the actual regex rule

'(?:(?<=^|\s)(?=\S|$)|(?<=^|\S)(?=\s|$))'.$myitem.'(?:(?<=^|\s)(?=\S|$)|(?<=^|\S)(?=\s|$)) *([ab])'

Now in this situation how do I count the backreference number as I see some conditional groupings as well.

Upvotes: 2

Views: 126

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191819

You can capture and replace:

$mystring = preg_replace('/'.$myitem.'([ab])/', "\1", $mystring);

Upvotes: 2

anubhava
anubhava

Reputation: 786329

You can capture and use backrefence in replacement:

$mystring = preg_replace('/'.$myitem.'([ab])/', '$1', $mystring);

Upvotes: 4

Related Questions