phpregexreplacecase-sensitive

Replace words and maintain case-sensitivity of the found string


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

Solution

  • 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
       
    ?>