Search code examples
phpregexpreg-replace-callback

Preg Replace Pattern Confusion with Single Quotes


I have the below pattern which works fine but I'm trying to add in a case for single quote but no matter what I do I can't get the single quote to work with the pattern, I've tried escaping is etc. with no luck!?

$title = preg_replace_callback('/(\"|\()([a-z])/', function($m) {
     return strtoupper($m[0]);
}, $title);

I've tried the below but it doesn't seem to work.

'/(\"\'|\()([a-z])/'

Solution

  • Just put all the three chars inside a character class. This \"\' would look for double quote as-well as the following single quote. If there isn't any , then it won't do the replacement.

    $title = '"foo(bar)"';
    echo preg_replace_callback('/[\'"(]([a-z])/', function($m) {
         return strtoupper($m[0]);
    }, $title);
    

    Output:

    "Foo(Bar)"