更新时间:2022-05-19 16:04:29
对于普通情况,我已经想到了此实现:
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"
-当然更复杂,但是适合任何职位的原始要求.如果您只寻找第一个字母,这可能是一个过大的选择(请参阅@Jon的回答)
-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)