Search code examples
regexspecial-characters

How to get just one special character in a string before a letter and insert a comma between them?


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.


Solution

  • 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.