php - 替换单词并保持找到的字符串区分大小写

标签 php regex replace case-sensitive

我正在创建一个 php 应用程序来格式化文件。所以我需要在维护案例的同时应用查找替换过程。

例如,我需要将“员工”替换为“车辆”。

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

echo str_ireplace($f, $r, $file_content);
   

当前输出:

vehicles are vehicles_category Myvehicles kitvehiclesMATCH

期望的输出:

Vehicles are vehicles_category MyVehicles kitVEHICLESMATCH

最佳答案

您可以通过分别替换每个案例来使用类似的东西:

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

     $res = str_replace($f, $r, $file_content); // replace for lower case
     $res = str_replace(strtoupper($f), strtoupper($r), $res); // replace for upper case
     $res = str_replace(ucwords($f), ucwords($r), $res); // replace for proper case (capital in first letter of word)
     echo $res
   
?>

关于php - 替换单词并保持找到的字符串区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65366654/

相关文章:

PHP 用单个正则表达式模式替换所有实例

javascript - 如何将值发布到输入框中?

php - 将文本中的 YouTube 链接替换为特定的嵌入代码

python - 使用字典和正则表达式重命名列名

python - 在 Python 中验证字符串值

c++ - 根据中间字母替换(反转)代码

php在ajax完成之前运行

java - 字符串替换函数无法正确替换字符 - Java

r - 根据频率更改 R 中数据帧的值

java - 如何提取单行源代码注释之间的文本?