2

I would like to check a string and convert all the substrings that could be potential links inside the original string like http://www.google.com, or www.google.com, replaced with <a href='http://www.google.com'>http://www.google.com</a> so that i can create real links from them.

How can i do this?

3

2 Answers 2

1

you can create the HTML links by calling the following function in PHP:

$stringToCheck = 'http://www.google.com, or www.google.com';
$stringWithHTMLLinks = '';

$stringWithHTMLLinks = preg_replace('/\b((https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[A-Z0-9+&@#\/%=~_|]/si', '<a href="\0">\0</a>', $stringToCheck);
Sign up to request clarification or add additional context in comments.

1 Comment

the h*ttp://www.google.com works fine but the www.google.com gives me localhost/migo2/www.google.com on localhost
0

Use this regex provided on Daring Fireball to match an URL.

4 Comments

i'll be sure to check it out :)
Here is the full version (IT IS LONG): (?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s!()[]{};:'".,<>?«»“”‘’]))`
Here is the shortened version (only matching http addresses): (?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s!()[]{};:'".,<>?«»“”‘’]))`
Also from Daring Fireball's page above: Update: A few readers have asked what the licensing terms are for using this pattern in their own code. This pattern is free for anyone to use, no strings attached. Consider it public domain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.