PHP preg_replace:不区分大小写与区分大小写的替换匹配


PHP preg_replace: Case insensitive match with case sensitive replacement

我在PHP中使用preg_replace来查找和替换字符串中的特定单词,如下所示:

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

这给出了"梨梨"的结果。

我希望能够做的是以不区分大小写的方式匹配一个单词,但在替换时尊重它的大小写 - 给出结果"梨梨"。

以下有效,但对我来说似乎有点冗长:

$pattern = array('/Apple'b/', '/apple'b/');
$replacement = array('Pear', 'pear');
$subject = "Apple apple";
print preg_replace($pattern, $replacement, $subject);

有没有更好的方法可以做到这一点?

更新:除了下面提出的一个很好的查询之外,出于此任务的目的,我只想尊重"标题大小写" - 因此,无论单词的第一个字母是否是大写字母。

我想到了常见情况的这个实现:

$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的答案(

你可以用preg_replace_callback做到这一点,但这更冗长:

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

此代码仅查看匹配的第一个字符的大小写,以确定要替换的内容;您可以调整代码以执行更复杂的操作。

这是我使用的解决方案:

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

我能做的最好的话,我将尝试解释为什么它有效:用()包装您的搜索词意味着我想稍后访问此值。由于它是正则表达式中 pars 中的第一项,因此可以通过 $1 访问它,正如您在替换参数中看到的那样

$text = 'Grey, grey and grey';
$text = Find_and_replace_in_lowercase_and_uppercase('grey', 'gray', $text);
echo $text; //Returns 'Gray, gray and gray'
function Find_and_replace_in_lowercase_and_uppercase($find_term, $replace_term, $text)
{
        $text = Find_and_replace_in_lowercase($find_term, $replace_term, $text);
        $text = Find_and_replace_in_uppercase($find_term, $replace_term, $text);
        return $text;
}
function Find_and_replace_in_lowercase($find_term, $replace_term, $text)
{
        $find_term = lcfirst($find_term);
        $replace_term = lcfirst($replace_term);
        $text = preg_replace("/$find_term/",$replace_term,$text);
        return $text;
}
function Find_and_replace_in_uppercase($find_term, $replace_term, $text)
{
        $find_term = ucfirst($find_term);
        $replace_term = ucfirst($replace_term);
        $text = preg_replace("/$find_term/",$replace_term,$text);
        return $text;
}