Skip to content
PHP Logo

How can recursive search and replace functions be implemented effectively in PHP?

Recursive search and replace functions can be implemented effectively in PHP by using a recursive function that traverses through nested arrays or strings, replacing the target value with the desired replacement value. The function should check if the current element is an array, and if so, recursively call itself to search and replace within that array. This approach ensures that all occurrences of the target value are replaced within nested structures.

php
function recursiveSearchReplace(&$input, $target, $replacement) {
    if (is_array($input)) {
        foreach ($input as $key => &$value) {
            recursiveSearchReplace($value, $target, $replacement);
        }
    } else {
        $input = str_replace($target, $replacement, $input);
    }
}

$data = [
    'name' => 'John',
    'age' => 30,
    'address' => [
        'street' => '123 Main St',
        'city' => 'New York',
        'zip' => '10001'
    ]
];

$target = 'New York';
$replacement = 'Los Angeles';
recursiveSearchReplace($data, $target, $replacement);

print_r($data);