By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,949 Members | 1,869 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,949 IT Pros & Developers. It's quick & easy.

Using regexp to replace url with hyperlink.

Markus
Expert 5K+
P: 6,050
Now, i've put my hand to this and it just burns me..

How would i go about taking some user input
[php]
$_userInput = "http://www.somesite.com is a great site!";
[/php]
and changing it so that it was wrapped in a hyperlink
[php]
$_userInput = "<a href=\"http://www.somesite.com\">http://www.somesite.com</a> is a great site!";
[/php]

Any ideas?
Much appreciated.
Feb 13 '08 #1
Share this Question
Share on Google+
3 Replies


ronverdonk
Expert 2.5K+
P: 4,258
Try this one for you.
[php]$pattern_url = '~(?>[a-z+]{2,}://|www\.)(?:[a-z0-9]+(?:\.[a-z0-9]+)?@)?(?:(?:[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])(?:\.[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])+|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?:/[^\\/:?*"<>|\n]*[a-z0-9])*/?(?:\?[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?(?:&[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?)*)?(?:#[a-z0-9_%.]+)?~i';

$text="http://www.somesite.com is a great site!";
echo preg_replace($pattern_url,"<a href=\"\\0\">\\0</a>", $text);[/php]
Ronald
Feb 13 '08 #2

Markus
Expert 5K+
P: 6,050
Try this one for you.
[php]$pattern_url = '~(?>[a-z+]{2,}://|www\.)(?:[a-z0-9]+(?:\.[a-z0-9]+)?@)?(?:(?:[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])(?:\.[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])+|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?:/[^\\/:?*"<>|\n]*[a-z0-9])*/?(?:\?[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?(?:&[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?)*)?(?:#[a-z0-9_%.]+)?~i';

$text="http://www.somesite.com is a great site!";
echo preg_replace($pattern_url,"<a href=\"\\0\">\\0</a>", $text);[/php]
Ronald
Works a charm, ronver!

Could you grace me with the logic behind it all, please?
Feb 13 '08 #3

ronverdonk
Expert 2.5K+
P: 4,258
When I can find the time I will. Made this one, after nights of sweat, many years ago and I still use it.

Ronald
Feb 13 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.