Home > Software engineering >  PHP replace patterns in string with URLs
PHP replace patterns in string with URLs

Time:12-31

I have a few hundred html files that I want to show on a website. They all have links in them in the following format:

[My Test URL|https://www.mywebsite.com/test?param=123]

The problem is that some urls are split up so:

[My Test URL|https://www.mywebsite.c om/test?param=123]

I want to replace all of those with the HTML counter-part so:

<a href="https://www.mywebsite.com/test?param=123">My Test URL</a>

I know that with the regex "/[(.*?)]/" I can match the brackets but how can I split by the pipe, remove the whitespaces in the URL and convert everything to a string?

CodePudding user response:

If you want to remove all WHITESPACES from a string in php all you need to do is:

$string = str_replace(' ', '', $string);

Where $string is your string with the url.

CodePudding user response:

I think this will do it for you

$html = "[My Test URL|https://www.mywebsite.c om/test?param=123] [My Test URL|https://www.mywebsite.com/test?param=123]";
$html = preg_replace_callback("|\[.*?\|.*?\]|", function($matches){
    list($anchor, $link) = explode("|",substr($matches[0], 1, -1));
    return "<a href='".str_replace(' ', '', $link)."'>$anchor</a>";
}, $html);

echo $html;
// echos  <a href="https://www.mywebsite.com/test?param=123">My Test URL</a> <a href="https://www.mywebsite.com/test?param=123">My Test URL</a>
  • Related