I'm trying to insert a comma between a string, like hello)))how are you
, I just want to insert it between the )
+ letter, I mean, hello))),how are you
.
How can I do this using regular expressions and preg_replace
?
I have tried using "/(\)+[a-z]){1}/g"
but it takes all the )
, not just the first one before the letter.
You may use
$result = preg_replace('~\)+\K(?=[a-z])~', ',', $s);
See the regex demo. Case insensitive variation: '~\)+\K(?=[a-z])~i'
.
Details
\)+
- matches 1+ )
chars\K
- omits the matched )
chars from the match(?=[a-z])
- requires a lowercase letter immediately to the right of the current location without adding it to the match value.Alternative:
$result = preg_replace('~(\)+)([a-z])~', '$1,$2', $s);
See this regex demo. Case insensitive variation: '~(\)+)([a-z])~i'
.
Here, (\)+)([a-z])
captures the close parentheses into Group 1 and then the letter is captured into Group 2 and the replacement is the value in Group 1 + ,
+ the value in Group 2.