Search code examples
phpurlhyperlinkstr-replacehtmlspecialchars

PHP: Wrap links from string between <a> </a> tags


I have this PHP code:

$y = $_POST['message'];

$pre = htmlspecialchars($y, ENT_QUOTES);

$msg = str_replace("&lt;br&gt;", "<br>", $pre);

That replaces all the converted <br>'s (&lt;b&gt;) back to <br>. And I am trying to do the same (well, almost) with all the links, somewhat like in the forums. Example...

http://www.example.com

Should be wrapped around like this:

<a href="http://www.example.com">http://www.example.com</a>

IF it's easier, I would obviously prefer the [URL] [/URL] method, likewise, [IMG] [/IMG].

Could someone point me in the right direction? I have been looking for hours here, and nothing adjusts to my need :/


Solution

  • A VERY simple way of doing it:

    $input = '[URL]xxx[/URL]';
    
    $url = explode('[URL]', $input);
    $url = explode('[/URL]', $url[1]);
    $url = '<a href="' . $url[0] . '"/>Link</a>';
    
    echo $url;
    

    There are most certainly better ways of doing this. Maybe with regex or preg_replace.