Badr
Badr

Reputation: 197

PHP replace all occurences with preg_replace_callback

I have a variable that contains a text, and i need to replace all occurrences that match a certain regular expression, each occurrence has to be changed by the result of a function that processes that occurrence's so i have to use preg_replace_callback() in order to pass each match to a callback that will then return the text to replace it. here is my code:

$fileContent = preg_replace_callback('/^.*video.*controls.*video.*$/m', function($matches){
                    foreach($matches as $k => $match){
                        $matches[$k] = str_replace('controls','controls controlsList="nodownload"', $match);
                    }
                    return $matches;
                }, $fileContent);

This causes an error since the function must return a string, but i don't understand how it expects an array of matches as a parameter and return a string ?

Upvotes: 1

Views: 2705

Answers (1)

Toto
Toto

Reputation: 91385

You don't have any capture groups, the match is in $matches[0].

Use:

$fileContent = preg_replace_callback('/^.*video.*controls.*video.*$/m', function($matches){
                        $matches[0] = str_replace('controls','controls controlsList="nodownload"', $match);
                    return $matches[0];
                }, $fileContent);

But, in your case, it is enough to do:

$fileContent = preg_replace('/^(.*video.*)controls(.*video.*)$/m', '$1controls controlsList="nodownload"$2', $fileContent);

Upvotes: 1

Related Questions