开发者

PHP preg_replace backreference causing undefined constant notice

开发者 https://www.devze.com 2023-03-29 01:28 出处:网络
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.

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)(开发者_如何学JAVA[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


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
);
0

精彩评论

暂无评论...
验证码 换一张
取 消