Find URLs in Text, Make Links
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text);
} else {
// if no urls in the text just return the text
echo $text;
}
?>
The basic function of this is to find any URLs in the block of text and turn them into hyperlinks. It will only find URLs if they are properly formatted, meaning they have a http, https, ftp or ftps.
Check out the comments below for more solutions.
I want to thank you from the bottom of my little heart, I have been in search for this exact script for the past 6 months! Thank you, thank you, thank you. I would like to point out however that there was error but nothing I could not fix :D Assid from your code this is the code that I got to work for myself.
<?php // The Regular Expression filter $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; // The Text you want to filter for urls $text = "The text you want to filter goes here. http://google.com"; // Check if there is a url in the text if(preg_match($reg_exUrl, $text, $url)) { // make the urls hyper links echo preg_replace($reg_exUrl, '<a href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text); } else { // if no urls in the text just return the text echo $text; } ?>Again thank you very much!
great!!! ela
This doesn’t work for 2 or more URLs.
Try using a loop => solved my problem when getting the data via MySQL
Add “g” to the end of the regexp to catch all instances.
Find the Image URL using preg_match() syntax or something similar to extract JPG or PNG or GIF URLs from a mixed text and put them in an array or at last store the first url.
maybe some syntax which searchs for strings that are beginning with http and ending with jpg/png/gif..
i believe it can be done with preg_match()
Note: the text can be like that : $string =blablablabla”http://www.xxx.com/xxx.jpg”blablablabla
$matches = array();
preg_match_all(‘!http://.+\.(?:jpe?g|png|gif)!Ui’ , $string , $matches);
Thanks,
It works like charm!
This is my version based on previous examples… hope this helps someone trying to force links on www without the http…
simply call the function as follows:
$body = txt2link($body);
When using the above codes inside a loop (wherein bulleted lists are created that have text/links in them) I get a server error if there’s more than one list item with a url that needs to be converted. Any way to do this in a foreach?
Thanks!
Cases that this won’t catch:
http://localhost/test
http://1.2.3.4/test
Also if you feed in
“http://www.google.co.uk/page is on the website http://www.google.co.uk/”
you will get some very mangled output, as when you search for “http://www.google.co.uk/” you will also match the text in the middle of the existing link for “http://www.google.co.uk/page”
your site is amazing. no bull shit. all good stuff. pls include my email id in ur permanent mailing list.
can that original script for finding urls be modifed to look for links ending with an .mp3 exstension?
Thanks, working a charm!
Great post. Just what I was looking for. I’m going to use it on my site.
Thanks.
Another equivalent function that make better results : http://code.seebz.net/p/autolink-php/
There is the same in javascript : http://code.seebz.net/p/autolink-js/
The domain name can be longer then 3 characters, e.g. http://cxid.info/
Great trick for developing the regular expression.
I’ve changed it a little bit, cause it won’t work for more than one url. Besides THANK YOU very much for the help.
i really liked this preg :D
is there a demo of this? i’ve been trying to put a url in a class on a div that will make the text in the div a link WIthout having to use the in the html markup. Is this overkill on unobtrusive css?
Hi guys
This way is much easier. The cost converts URLs in $Text to html hyper links:
if (preg_match(“/http/”, “$Text”) OR preg_match(“/www/”, “$Text”))
{
$ExplodeText = explode(” “, $Text);
foreach($ExplodeText as $Check)
{if (preg_match(“/http/”, “$Check”) OR preg_match(“/www/”, “$Check”)) {$Text = str_replace($Check , “$Check” , $Text);}}
}
Apologies, there was a mistake in the code I post above. Below is the corrected version:
if (preg_match(“/http/”, “$Text”) OR preg_match(“/www/”, “$Text”))
{
$Text = str_replace(” www” , ” http://www” , $Text);
$Explode = explode(” “, $Text);
foreach($Explode as $Check) {if (preg_match(“/http/”, “$Check”) OR preg_match(“/www/”, “$Check”)) {$Text = str_replace($Check , “$Check” , $Text);}}
}
please list my email id in your mailing lists i would like to be notified about all the stuffs discussed here thanks!
Great regex, thankyou! Here’s a single preg_replace that doesn’t need a loop and catches both http:// or www.
$text = “check out my link http://mylink.com or http://www.otherlink.com works too”;
$reg_exUrl = “/((((http|https|ftp|ftps)\:\/\/)|www\.)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}(\/\S*)?)/”;
echo preg_replace( $reg_exUrl, “<a href=\"$1\">$1</a> “, $text );
Addendum: actually, it treats www. links as local links, so further work needs to be done on that.
Hi, If the url has ‘%20′ how can I make it?
Example: http://www.lalala.com/%20text%20some.html
Can you help me?
Thank you
Regards
replace the %20 beforehand
Thanks for this tutorial. I happy. It work… :)
Can some on post or email me the COMPLETE SCRIPT FINALLY WHICH CAN FIND ALL URLS IN A PAGE AND HIGHLIGHT THEM AS LINKS
I am requesting as i do not know coding for my self as i am not into web-designing
This is great article but it can’t handle certain situation so i modified it bit so check the article below that works great with possible all situation…
http://www.javaquery.com/2012/06/turn-urls-into-links-in-text-with.html
actualy everything is much easier)
*
much easier than write a comment with code on this site XD
****, kk there should be “href=”\”>\” in the ancor tag
grrrrrrrrrrrrrrrrrrrr THIS IS THE LINK 4 SOLUTION
Yep. It’s much easier… lol
Tks for your persistence. Your code worked…
I have a chat log i want to get all links out of. How do i use this code to do this?
*I am not a programmer*
can i run some kind of batch command file or something and point to the text log?
echo preg_replace($reg_exUrl, “{$url[0]} “, $text);
In above code
“{$url[0]}” => ‘{$url[0]}’
fix my problem
I keep having error on this line
echo preg_replace($reg_exUrl, “{$url[0]} “, $text);
I think it has to be from “{$url[0]}” and {$url[0]}
can anyone help me on whats going on
Yep, you should change it to
echo preg_replace($reg_exUrl, “.$url[0].“, $text);
i made some changes on it to work with multiple links
Hello to every single one, it’s really a fastidious for me to visit this web site, it contains useful Information.
Yep!! Another very usefull snippet!! Another bookmark to css ticks ;)
It has syntax errors too.Below is the correct code:
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "{$url[0]} ", $text);
} else {
// if no urls in the text just return the text
echo $text;
}
?>
//easy—>worked for me
$data =”my text http://www.facebook.com/c.hodari90“;
$data = preg_replace( ‘/(http|ftp)+(s)?:(\/\/)((\w|.)+)(\/)?(\S+)?/i’, ‘\4‘, $data );
echo $data;
output = my text facebook.com/c.hodari90
Proposed code has a slight flaw. If $text contains two similar URLs, like “The text you want to filter has two URLs namely http://google.com but also http://google.com/index.html#hashtag” with both URLs starting the same, then the #hashtag in the second URL gets lost.
Since URLs inside a string are separated by spaces (I believe this is always the case), the following code works for me:
// The Regular Expression filter $reg_exUrl = "/(https?|ftps?|file):\/\/([a-z0-9]([a-z0-9_-]*[a-z0-9])?\.)+[a-z]{2,6}\/?([a-z0-9\?\._-~&#=+%]*)?/i"; // The Text you want to filter for URLs $text = "The text you want to filter has two URLs namely http://google.com but also http://google.com/index.html#hashtag"; // add leading and trailing spaces they serve as URL delimiters in case // the URL is at the very beginning or end of $text $text = " ".$text." "; // Check if there is a url in the text if(preg_match_all($reg_exUrl, $text, $url)) { // make the URL hyper links $matches = array_unique($url[0]); foreach($matches as $match) { $replacement = "<a href=".$match.">".$match.""; $text = str_replace(" ".$match." ", " ".$replacement." ", $text); } // if URLs in the text, return the text after // removing the leading and trailing spaces $text = trim(nl2br($text), " "); } else { // if no URLs in the text, return the original text after // removing the leading and trailing spaces echo trim($text, " "); }By the way, I use a different regex which does not match URLs that contain forbidden characters like @
Anf finally… what a pain in the back to get this comment displayed the right way (I hope…).