You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP文件格式化开发:实现匹配原大小写的字符串替换功能

实现保留原字符串大小写的查找替换

刚好之前遇到过类似的需求,str_ireplace确实满足不了这种大小写感知的替换——它只会忽略大小写查找,但替换时直接用固定的目标字符串,所以得用正则配合回调函数来实现,根据原匹配内容的大小写模式动态生成替换文本。

解决方案代码

$file_content = "Employees are employees_category MyEmployees kitEMPLOYEESMATCH";
$f = 'employees';
$r = 'vehicles';

// 转义查找字符串中的正则特殊字符,避免破坏正则表达式
$pattern = '~' . preg_quote($f, '~') . '~i';

$result = preg_replace_callback($pattern, function($matches) use ($r) {
    $originalMatch = $matches[0];
    
    // 情况1:原匹配字符串全大写
    if (ctype_upper($originalMatch)) {
        return strtoupper($r);
    }
    // 情况2:原匹配字符串首字母大写、其余小写(比如Employees)
    elseif (ucfirst(strtolower($originalMatch)) === $originalMatch) {
        return ucfirst($r);
    }
    // 情况3:原匹配字符串全小写
    elseif (ctype_lower($originalMatch)) {
        return strtolower($r);
    }
    // 情况4:混合大小写(比如EmpLoyEes),逐个字符对应大小写
    else {
        $lowercaseReplacement = strtolower($r);
        $finalReplacement = '';
        for ($i = 0; $i < strlen($originalMatch); $i++) {
            $originalChar = $originalMatch[$i];
            // 确保替换字符不越界(如果原匹配比替换字符串长,后面的字符留空,可按需调整)
            $replacementChar = $i < strlen($lowercaseReplacement) ? $lowercaseReplacement[$i] : '';
            $finalReplacement .= ctype_upper($originalChar) ? strtoupper($replacementChar) : $replacementChar;
        }
        return $finalReplacement;
    }
}, $file_content);

echo $result;

代码说明

  • 正则模式:用~作为分隔符,i修饰符实现忽略大小写查找,preg_quote处理查找字符串中的正则特殊字符(比如.、*等),避免正则语法错误。
  • 回调函数逻辑:
    • 先判断原匹配字符串的大小写类型,分别返回对应格式的替换文本;
    • 针对混合大小写的极端情况,逐个字符匹配原字符的大小写,保证替换后的格式和原字符串一致;
  • 变量传递:匿名函数通过use ($r)访问外部的替换目标字符串。

运行这段代码后,输出就是你期望的:

Vehicles are vehicles_category MyVehicles kitVEHICLESMATCH

内容的提问来源于stack exchange,提问作者Shihabu Rahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:09:44