PHP preg_replace: Case insensitive match with case sensitive replacement

后端 未结 3 1959
囚心锁ツ
囚心锁ツ 2020-12-14 07:39

I\'m using preg_replace in PHP to find and replace specific words in a string, like this:

$subject = \"Apple apple\";
print preg_replace(\'/\\bapple\\b/i\',          


        
3条回答
  •  余生分开走
    2020-12-14 08:23

    You could do this with preg_replace_callback, but that's even more long winded:

    $replacer = function($matches) {
        return ctype_lower($matches[0][0]) ? 'pear' : 'Pear';
    };
    
    print preg_replace_callback('/\bapple\b/i', $replacer, $subject);
    

    This code just looks at the capitalization of the first character of the match to determine what to replace with; you could adapt the code to do something more involved instead.

提交回复
热议问题