Jump to content

[SOLVED] Enclose URL in tags?


immanuelx2

Recommended Posts

Hey guys, wondering if someone could point me to a sample preg_replace() function that searches for an URL of any kind and encloses it in tags

 

The one I found so far is

<?php
$text = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $text);

 

but for some reason, if the URL contains a dash "-" it thinks the URL has ended.. ???

 

Thanks in advance

Link to comment
https://forums.phpfreaks.com/topic/163931-solved-enclose-url-in-tags/
Share on other sites

kind of simple but it should do the trick most of the time....idea here is that if something starts with http:// or https:// then it's probably a url, so it just grabs everything up to the first space it finds.  The theory being that a url would not have a space in it (or it would be urlencoded so it wouldn't be a physical space char)

 

$text = preg_replace('~(https?://[^\s]+)~i','<a href= "$1">$1</a>',$text);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.