CodeIgniter Forums
Need regex help to replace links in a string - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Need regex help to replace links in a string (/showthread.php?tid=26332)



Need regex help to replace links in a string - El Forum - 01-11-2010

[eluser]ehicks727[/eluser]
I've got a string that I need to turn properly formatted urls into anchor text.

For example...

Code:
$string = "http://www.example.com"

turns into...

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

I appreciate the help!! Thank you.


Need regex help to replace links in a string - El Forum - 01-11-2010

[eluser]Dyllon[/eluser]
Code:
$string = "http://codeigniter.com";

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



Need regex help to replace links in a string - El Forum - 01-11-2010

[eluser]ehicks727[/eluser]
Sweet! thanks, worked great.


Need regex help to replace links in a string - El Forum - 01-11-2010

[eluser]danmontgomery[/eluser]
http://ellislab.com/codeigniter/user-guide/helpers/url_helper.html

Quote:auto_link()

Automatically turns URLs and email addresses contained in a string into links. Example:
$string = auto_link($string);

The second parameter determines whether URLs and emails are converted or just one or the other. Default behavior is both if the parameter is not specified. Email links are encoded as safe_mailto() as shown above.

Converts only URLs:
$string = auto_link($string, 'url');

Converts only Email addresses:
$string = auto_link($string, 'email');

The third parameter determines whether links are shown in a new window. The value can be TRUE or FALSE (boolean):
$string = auto_link($string, 'both', TRUE);



Need regex help to replace links in a string - El Forum - 01-11-2010

[eluser]ehicks727[/eluser]
Ah, forgot about that helper. Thank you. That actually worked better (sorry Dyllon) because the regex above does not catch dashes in the url.


Need regex help to replace links in a string - El Forum - 01-11-2010

[eluser]sophistry[/eluser]
i fixed auto_link() a few months back. there were a lot of problems with it.

this links to the second page of the discussion, but has the full code (linked onto pastebin because of EE's"loose" handling of entities (i.e., it mangled them).
http://ellislab.com/forums/viewthread/95384/P15/