PHP preg_replace: Case insensitive match with case sensitive replacement

后端 未结 3 1952
囚心锁ツ
囚心锁ツ 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:17

    This is the solution that I used:

    $result = preg_replace("/\b(foo)\b/i", "<strong>$1</strong>", $original);
    

    In the best words that I can I'll try explain why this works: Wrapping your search term with () means I want to access this value later. As it is the first item in pars in the RegEx, it is accessible with $1, as you can see in the substitution parameter

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-14 08:33

    I have in mind this implementation for common case:

    $data    = 'this is appLe and ApPle';
    $search  = 'apple';
    $replace = 'pear';
    
    $data = preg_replace_callback('/\b'.$search.'\b/i', function($matches) use ($replace)
    {
       $i=0;
       return join('', array_map(function($char) use ($matches, &$i)
       {
          return ctype_lower($matches[0][$i++])?strtolower($char):strtoupper($char);
       }, str_split($replace)));
    }, $data);
    
    //var_dump($data); //"this is peaR and PeAr"
    

    -it's more complicated, of course, but fit original request for any position. If you're looking for only first letter, this could be an overkill (see @Jon's answer then)

    0 讨论(0)
提交回复
热议问题