Search code examples
phpregexcamelcasing

PHP preg_replace backreference causing undefined constant notice


I'm trying to use NameCase a php class on code.google.com. When I run it I get this notice and I don't understand why.

PHP Notice: Use of undefined constant Mc - assumed 'Mc' in namecase.php(54) : regexp code on line 1

53   if( preg_match('/\bMac[A-Za-z]{2,}[^aciozj]\b/', $str) || preg_match('/\bMc/', $str) ) {
54     $str = preg_replace("/\b(Ma?c)([A-Za-z]+)/e", "$1.ucfirst('\\2')", $str);
55     // Now correct for "Mac" exceptions
56     $str = preg_replace('/\bMacEvicius/','Macevicius', $str); // Lithuanian
57     $str = preg_replace('/\bMacHado/',   'Machado', $str);    // Portuguese
58     $str = preg_replace('/\bMacHar/',    'Machar', $str);
59     ...

Is there anything that can be done to correct the code so it doesn't produce the notice.

Thanks


Solution

  • You need to quote the $1 in your replacement, e.g. "'$1'.ucfirst('\\2')" or better yet, use preg_replace_callback. In PHP 5.3+ you can pass it a closure, e.g:

    $str = preg_replace_callback(
        "/\b(Ma?c)([A-Za-z]+)/",
        function($m) { return $m[1] . ucfirst($m[2]); },
        $str
    );