Php 替换单词并保持找到的字符串区分大小写
我正在创建一个php应用程序来格式化文件。因此,我需要在维护案例的同时应用查找-替换过程 例如,我需要将“员工”替换为“车辆”Php 替换单词并保持找到的字符串区分大小写,php,regex,replace,case-sensitive,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); 电流输出: vehic
$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
?>
虽然SJ11的答案因其简洁而吸引人,但它很容易在已经替换的子字符串上进行意外替换,尽管OP的示例数据不可能 若要确保不替换替换项,必须仅对输入字符串进行一次传递 对于实用程序,我将包括
preg_quote()
,这样当$r
值包含正则表达式中具有特殊含义的字符时,模式不会中断
代码:()()
输出:(单引号来自var\u export()
)
$file_content = "Employees are employees_category MyEmployees kitEMPLOYEESMATCH";
$f = 'employees';
$r = 'vehicles';
$pattern = '~('
. implode(
')|(',
[
preg_quote($f, '~'),
preg_quote(ucfirst($f), '~'),
preg_quote(strtoupper($f), '~')
]
) . ')~';
$lookup = [
1 => $r,
2 => ucfirst($r),
3 => strtoupper($r)
];
var_export(
preg_replace_callback(
$pattern,
function($m) use ($lookup) {
return $lookup[count($m) - 1];
},
$file_content
)
);
'Vehicles are vehicles_category MyVehicles kitVEHICLESMATCH'