Search code examples
phppreg-replacebackendpreg-replace-callback

PHP Regex replace multiple urls with itself with a return function


I have a site where I need to check and replace a text with href's in it, that's not the problem. But I have to localize the url, that's done with a function, but I can't get it to work together.

My code to replace the links:

$text = "this is a test text blabla <a href="https://example.com/test/">Test</a>";
$pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))+/";
$replace = '${0}';
echo preg_replace($pattern, $replace, $text);

I need to do the localize function over the $replace variable when I'm replacing the text. I know it can be done by using preg_replace_callback, I searched the internet but can't get it working.

My code to localize the url:

$replace = WPGlobus_Utils::localize_url($replace, 'en');
// This will replace the url from https://example.com/test/ to https://example.com/en/test/

Thanks in advance,

Remy


Solution

  • You need to use preg_replace_callback with the following slightly enhanced pattern:

    $pattern = "/(?<=href=[\"'])[^\"']+(?=[\"'])/";
    

    And then...

    $result = preg_replace_callback($pattern, function($m) { 
       return localize_url($m[0]);
    }, $text);
    

    Note that (\"|') is meant to match either " or ' and it is much better and efficient to use a character class instead, that is ["'].