3

I am creating a php application to format files. So I need to apply a find-replace process while maintaining the case.

For example, I need to replace 'employees' with 'vehicles'.

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

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

Current Output:

vehicles are vehicles_category Myvehicles kitvehiclesMATCH

Desired Output:

Vehicles are vehicles_category MyVehicles kitVEHICLESMATCH
mickmackusa
  • 43,625
  • 12
  • 83
  • 136

2 Answers2

1

You could use something like this by replacing for each case separately:

<?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
  • 244
  • 1
  • 3
0

While the SJ11's answer is attractive for its brevity, it is prone to making unintended replacements on already replaced substrings -- though not possible with the OP's sample data.

To ensure that replacements are not replaced, you must make only one pass over the input string.

For utility, I will include preg_quote(), so that pattern does not break when the $r value contains characters with special meaning in regex.

Code: (Demo) (PHP7.4 Demo)

$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
    )
);

Output: (single quotes are from var_export())

'Vehicles are vehicles_category MyVehicles kitVEHICLESMATCH'
mickmackusa
  • 43,625
  • 12
  • 83
  • 136