1

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

5
  • So after the TLD you need to add en/? Commented Apr 12, 2018 at 20:52
  • Yes, but that's not the problem. I first have to preg_replace all links in a string, and I need to localize (add en/ to the url) after the preg is going to be replaced. Commented Apr 12, 2018 at 21:05
  • 1
    1) Use $pattern = "/(?<=href=[\"'])[^\"']+(?=[\"'])/"; pattern 2) preg_replace_callback($pattern, function($m) { return localize_url($m[0]);}, $text); or something like that. Commented Apr 13, 2018 at 6:50
  • @WiktorStribiżew Thanks! I edited the code a bit and it worked great! :) Commented Apr 13, 2018 at 12:07
  • 1
    My last today's vote goes for you :) Commented Apr 13, 2018 at 12:09

1 Answer 1

1

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 ["'].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.