Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I linkify urls in a string with php?

Tags:

string

url

php

I have the following string:

"Look on http://www.google.com". 

I need to convert it to:

"Look on http://www.google.com"

The original string can have more than 1 URL string.

How do I do this in php?

Thanks

like image 989
Alex Avatar asked Feb 03 '09 15:02

Alex


2 Answers

You can use the following:

$string = "Look on http://www.google.com"; $string = preg_replace(               "~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~",               "<a href=\"\\0\">\\0</a>",                $string); 

PHP versions < 5.3 (ereg_replace) otherwise (preg_replace)

like image 82
Ben Avatar answered Sep 20 '22 22:09

Ben


lib_autolink does a pretty good job, avoiding pitfalls like extra punctuation after the link and links inside HTML tags:

https://github.com/iamcal/lib_autolink

like image 31
Cal Avatar answered Sep 19 '22 22:09

Cal