Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

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.

Comments

  1. David Moreen
    Permalink to comment#

    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!

  2. Dan Jasnowski
    Permalink to comment#

    This doesn’t work for 2 or more URLs.

    • Glenn Gahnstedt
      Permalink to comment#

      Try using a loop => solved my problem when getting the data via MySQL

    • Teddy
      Permalink to comment#

      Add “g” to the end of the regexp to catch all instances.

      /(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/g
  3. Vindesh Mohariya

    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);

  4. Dev

    Thanks,

    It works like charm!

  5. Wolandca
    Permalink to comment#
    public function formatUrlsInText($text){
                $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
                preg_match_all($reg_exUrl, $text, $matches);
                $usedPatterns = array();
                foreach($matches[0] as $pattern){
                    if(!array_key_exists($pattern, $usedPatterns)){
                        $usedPatterns[$pattern]=true;
                        $text = str_replace  ($pattern, "<a href="{$pattern}" rel="nofollow">{$pattern}</a> ", $text);   
                    }
                }
                return $text;            
    }
  6. amitai
    Permalink to comment#

    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);

    function txt2link($text){
    	// force http: on www.
     	$text = ereg_replace( "www\.", "http://www.", $text );
    	// eliminate duplicates after force
      	$text = ereg_replace( "http://http://www\.", "http://www.", $text );
      	$text = ereg_replace( "https://http://www\.", "https://www.", $text );
      
    	// The Regular Expression filter
    	$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    	// Check if there is a url in the text
    	if(preg_match($reg_exUrl, $text, $url)) {
    		   // make the urls hyper links
    		   $text = preg_replace($reg_exUrl, '<a href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text);
    	}    // if no urls in the text just return the text
    		   return ($text);
    }
    • Benjamin
      Permalink to comment#

      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!

  7. James
    Permalink to comment#

    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”

  8. goyal
    Permalink to comment#

    your site is amazing. no bull shit. all good stuff. pls include my email id in ur permanent mailing list.

  9. James
    Permalink to comment#

    can that original script for finding urls be modifed to look for links ending with an .mp3 exstension?

  10. DanJenkins
    Permalink to comment#

    Thanks, working a charm!

  11. Miguel Mdz
    Permalink to comment#

    Great post. Just what I was looking for. I’m going to use it on my site.

    Thanks.

  12. Seebz

    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/

  13. braz
    Permalink to comment#

    The domain name can be longer then 3 characters, e.g. http://cxid.info/

  14. omprakash
    Permalink to comment#

    Great trick for developing the regular expression.

  15. Petar Marinov
    Permalink to comment#

    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.

    public static function url_to_link($text) {
                // The Regular Expression filter
                $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
                // Check if there is a url in the text
                if (preg_match_all($reg_exUrl, $text, $url)) {
                    // make the urls hyper links            
                    foreach($url[0] as $v){                
                        //current position of the searached url
                        $curpos = strpos($text,' '.$v)+1;
                        //delete the url                
                        $text = substr_replace($text,'', $curpos, strlen($v));
                        //insert the link
                        $text = substr_replace($text,''.$v.'', $curpos ,0);                
                    }
                    return $text;
                } 
                else {
                    // if no urls in the text just return the text
                    return $text;
                }
            }
  16. milad
    Permalink to comment#

    i really liked this preg :D

  17. chris
    Permalink to comment#

    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?

  18. Steve
    Permalink to comment#

    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);}}
    }

  19. Steve
    Permalink to comment#

    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);}}
    }

  20. Nishchal Gautam
    Permalink to comment#

    please list my email id in your mailing lists i would like to be notified about all the stuffs discussed here thanks!

  21. youlweb
    Permalink to comment#

    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 );

    • youlweb
      Permalink to comment#

      Addendum: actually, it treats www. links as local links, so further work needs to be done on that.

  22. codezer
    Permalink to comment#

    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

  23. Sumanta Kundu

    Thanks for this tutorial. I happy. It work… :)

  24. iKnowledge

    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

  25. Vicky

    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

  26. Modi
    Permalink to comment#

    actualy everything is much easier)

    $text=preg_replace("#(https?|ftp)://\S+[^\s.,>)\];'\"!?]#",'\',$text);
  27. Modi
    Permalink to comment#

    *

    <?php
    
    
     $text=preg_replace("#(https?|ftp)://\S+[^\s.,>)\];'\"!?]#",'class="pun"><a href="\">\',$text); ?>

    much easier than write a comment with code on this site XD

  28. Modi
    Permalink to comment#

    ****, kk there should be “href=”\”>\” in the ancor tag

  29. Modi
    Permalink to comment#

    grrrrrrrrrrrrrrrrrrrr THIS IS THE LINK 4 SOLUTION

    • Hisamitsu
      Permalink to comment#

      Yep. It’s much easier… lol
      Tks for your persistence. Your code worked…

  30. fabes
    Permalink to comment#

    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?

  31. rck
    Permalink to comment#

    echo preg_replace($reg_exUrl, “{$url[0]} “, $text);
    In above code
    “{$url[0]}” => ‘{$url[0]}’

    fix my problem

  32. Soladnet
    Permalink to comment#

    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

    • Andre
      Permalink to comment#

      Yep, you should change it to
      echo preg_replace($reg_exUrl, “.$url[0].“, $text);

  33. Ahmed
    Permalink to comment#

    i made some changes on it to work with multiple links

            function linkToAnchor($text) {
            // 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
    
            // Check if there is a url in the text
            if(preg_match_all($reg_exUrl, $text, $url)) {
                   // make the urls hyper links
                   $matches = array_unique($url[0]);
                   foreach($matches as $match) {
                        $replacement = "<a href=".$match.">{$match}</a>";
                        $text = str_replace($match,$replacement,$text);
                   }
                   return nl2br($text);
            } else {
    
                   // if no urls in the text just return the text
                   return nl2br($text);
    
            }
        }
    
    • Da Man
      Permalink to comment#

      This worked for me, but won’t work without http:// or https://, how would I add so it would work with www?

  34. Anonymous
    Permalink to comment#

    Hello to every single one, it’s really a fastidious for me to visit this web site, it contains useful Information.

  35. virneto
    Permalink to comment#

    Yep!! Another very usefull snippet!! Another bookmark to css ticks ;)

  36. Techya
    Permalink to comment#

    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, "<a href='$url[0]' rel="nofollow">{$url[0]}</a> ", $text);
    
        } else {
    
               // if no urls in the text just return the text
               echo $text;
    
        }
    ?>
    
  37. chris

    //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

  38. Innato

    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…).

    • Thomas Tesselaar
      Permalink to comment#

      Your code worked, but you forgot to close the tag!
      I changed
      $replacement = “
      “.$match.””;
      to
      $replacement = “
      “.$match.”“;

      Your code doesn’t print the text if there is an url present, therefor changed this:
      // if URLs in the text, return the text after
      // removing the leading and trailing spaces
      $text = trim(nl2br($text), ” “);
      to
      // if URLs in the text, return the text after
      // removing the leading and trailing spaces
      $text = trim(nl2br($text), ” “);
      echo $text;

      Hope this helps someone! :)

  39. Vasim Padhiyar
    Permalink to comment#

    Try this for multiple urls :

    function findURLs($text)
    {

        $pattern = '/[-a-zA-Z0-9@:%_\+.~#?&\/\/=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)?/i';
    
        @preg_match_all($pattern, $text, $matches);
    
        if($matches[0])
        {
            return $matches[0];
        }
        else
        {
            return false;
        }
    }
    
  40. Andrew
    Permalink to comment#

    I coded this myself before stumbling across this snippet – I needed to parse links in tweets stored in my site’s database.

    The only difference is that my version parses multiple links.

  41. mani
    Permalink to comment#

    search anyone how to get first link url in curl php

  42. mani
    Permalink to comment#

    plz help me

  43. Geert
    Permalink to comment#

    This works fine for me to format posted comments for publication:

    <?php
        $tekst = preg_replace ("'<[\/\!]*?[^]*?>'si", "", $tekst);
        $tekst =preg_replace("/(15)|(15)/"," ",$tekst);
        function formatUrlsInText($text){
                $text = ereg_replace( "www.", "http://www.", $text );
                $text = ereg_replace( "http://http://www.", "http://www.", $text );
                $text = ereg_replace( "https://http://www.", "https://www.", $text );
                $reg_exUrl = "/(http|https|ftp|ftps):\/\/[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(\/\S*)?/";
                preg_match_all($reg_exUrl, $text, $matches);
                $usedPatterns = array();
                foreach($matches[0] as $pattern){
                    if(!array_key_exists($pattern, $usedPatterns)){
                        $usedPatterns[$pattern]=true;
                        $text = str_replace  ($pattern, "<a href="{$pattern}" rel="nofollow">weblocatie</a> ", $text);
                    }
                }
                return $text;
        }
        $tekst = formatUrlsInText($tekst);
    
        echo $tekst;
    ?>
    
  44. jeni

    what is pattern to use for find email from url
    I tried this
    $reg_exUrl = ‘/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/';

            preg_match_all($reg_exUrl, $text, $matches);
            $usedPatterns = array();
            print_r($matches);
    

    not working pls help

  45. Chris

    I was looking for a solution that is lenient and allows for multiple urls formats with or without ‘http’ or ‘https’. None on this page worked for me, but I found a great script from markd on stackoverflow (http://stackoverflow.com/questions/1959062/how-to-add-anchor-tag-to-a-url-from-text-input)

    function hyperlinksAnchored($text) {
        return preg_replace('@(http)?(s)?(://)?(([-\w]+\.)+([^\s]+)+[^,.\s])@', '$1$2$3$4', $text);
    }

    It works for these URLs (and successfully leaves out trailing period or comma):

    http://www.google.com/
    
    https://www.google.com/.
    
    www.google.com
    www.google.com.
    www.google.com/test
    google.com
    google.com,
    google.com/test
    123.com/test
    www.123.com.au
    ex-ample.com
    
    http://ex-ample.com
    
    
    http://ex-ample.com/test-url_chars.php?param1=val1.
    
    
    http://ex-ample.com/test-url_chars?param1=value1&param2=val+with%20spaces
  46. url
    Permalink to comment#

    what exactly is these line

    $replacement = ““.$match.”

    i thinks is not working.

  47. Xavi
    Permalink to comment#

    Thanks for this post and the comments. Through it I’ve been able to improve very much my older code :). With this post original’s, there are a few gaps that need to be solved:

    1- As commented, you can’t have more than one URL in the text. This can be solved easily replacing “$url[0]” in the preg_replace() for “$1″

    2- The script doesn’t care if the http:// link in your original text is already inside a html link. For solving this, you have to modify the beginning of the reg exp. to match only strings that are at the beginning of the string, that begin with a space or new line code: (^|\A|\s)

    3- I want my code to catch URL’s starting with www. For this, I added another regexp filter also using the starting filter: (^|\A|\s). It won’t get “http://www.” links because before the “www” there are the slashes.

    // URL starting with http://
    $reg_exUrl = "/(^|\A|\s)((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}(\/\S*)?)/";
        if(preg_match($reg_exUrl, $textorigen, $url)) {
    
       // make the urls hyper links
       $text_result=preg_replace( $reg_exUrl, "$1<a href=\"$2\">$2</a> ", $textorigen );
    } else {
    
       // if no urls in the text just return the text
        $text_result=$textorigen;
    }   
    
    // URL starting www.
    $reg_exUrl = "/(^|\A|\s)((www\.)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}(\/\S*)?)/";
    if(preg_match($reg_exUrl, $text_result, $url)) {
    
       // make the urls hyper links
       $text_result=preg_replace( $reg_exUrl, "$1<a href=\"http://$2\">$2</a>", $text_result );
    }
    

    Hope this code helps someone. Comments allowed!

  48. Sebastian
    Permalink to comment#

    I was looking for a script that links existing images to their sourcefile with fancybox.
    I used the function from Geert and did some changes.

    function formatUrlsInText($text){
            $reg_exUrl = "/(<img[^>]+>)/i";
            preg_match_all($reg_exUrl, $text, $matches);
            $usedPatterns = array();
            foreach($matches[0] as $pattern){
                if(!array_key_exists($pattern, $usedPatterns)){
                    $usedPatterns[$pattern]=true;
                    //Link aus dem IMG Tag holen
                    $imgarray=explode('"', $pattern);
                    //Bildpfad aus URL holen ([6])
                    $linkarray=explode('/', $imgarray[1]);
    
                    $text = str_replace  ($pattern, '<a class="fancybox contentImages" rel="group" href=./uploads/'.$linkarray[6].'>'.$pattern.'</a>', $text);
                }
            }
            return $text;
    }
    $content = formatUrlsInText($content);
    
    echo $content;
    
  49. Neeraj
    Permalink to comment#

    $reg_exUrl = “/((((http|https|ftp|ftps):\/\/)|www.)[a-zA-Z0-9-.]+.[a-zA-Z]{2,4}(\/?\S*))/”;

    This is working fine with all query string and slashes

  50. Mark Goldsmith
    Permalink to comment#

    Here is a nice function that turns text into links, including email links (sorry no FTP).

    Instead of searching for any domain extension, I included the most popular ones, so that text like “example.fake” wouldn’t be considered a link. Other domain extensions can be easily added.

    This also takes into account periods and commas.

     function prependHTTP( $m )
     {
       $mStr = $m[1].$m[2].$m[3];
    
       // if its an email address
       if( preg_match('#([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#', $mStr))
       {
            return "<a href=\"mailto:".$m[2].$m[3]."\" target=\"_blank\">".$m[1].$m[2].$m[3]."</a>"; 
       }
       else
       {
        $http = (!preg_match("#(https://)#", $mStr)) ? 'http://' : 'https://';
        return "<a href=\"".$http.$m[3]."\" target=\"_blank\">".$m[1].$m[2].$m[3]."</a>"; 
        }   
     }
    
    function formatUrlsInText($text) 
    { 
       return preg_replace_callback('#(?i)(http|https)?(://)?(([-\w^@]+\.)+(net|org|edu|gov|me|com+)(?:/[^,.\s]*|))#','prependHTTP',$text);
    }
    

    It works for these values:

    google.com
    ALLCAPS.COM
    www.google.com/a
    
    http://www.google.com
    
    
    http://www.google.com/?querystring=something
    
    various-hyphens.com
    
    https://wonderwoman.org
    
    some-school.edu
    subdomain.yourwebsite.com
    person@website.com
    billgates.me
    

    These values fail:

     google.buzz
     myname.is
    
    http://hello
    
    
  51. Rolf
    Permalink to comment#

    Hi, I use the first code but how can I search for more words?
    and if the first word is found then go to A, and the second word is found go to B etc…

    // The Text you want to filter for urls
    $text = “The text you want to filter goes here. http://google.com“;

  52. sisir
    Permalink to comment#

    There should be another example using DOMDocument Class :)

  53. Ryan Burnette
    Permalink to comment#

    In WordPress I like to make this a filter so I can use it anywhere quickly and easily.

    function make_urls_in_text_func($text) {
      $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
      if(preg_match($reg_exUrl, $text, $url)) {
        return preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text);
      }
      else {
        return $text;
      }
    }
    add_filter('make_urls_in_text', 'make_urls_in_text_func');
    
  54. Christoffer
    Permalink to comment#

    The code with regex does not work completely.

    I made this code. It is much more comprehensive, but it works:

    See the result here: Your text to link here…

    See the source code here: Your text to link here…

  55. debute
    Permalink to comment#

    Here is my short code to replace all URLs in string. Hope I helped you.

    function replace($text){
          $text = ereg_replace("www\.", "http://www.", $text);
          $text = ereg_replace("http://http://www\.", "http://www.", $text);
          $text = ereg_replace("https://http://www\.", "https://www.", $text);
          $exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
          preg_match_all($exUrl, $text, $url);
          foreach($url[0] as $k=>$v) $text = str_replace($url[0][$k], '<a href="'.$url[0][$k].'" target="_blank" rel="nofollow">'.$url[0][$k].'</a>', $text);
          return $text;
        }
    
    $text = "Now, you can add URL http://www.google.co.uk/ and other URL will be replaced too https://www.google.sk/imghp";
    echo replace($text);
    
    • Joel
      Permalink to comment#

      Thank you! Original method does not work. Presents a syntax error. But this one works great! And having multiple urls in the string is a must.

  56. ffsplus2.com
    Permalink to comment#

    I have made function which will catch web link and image link

    This will catch all which ends with jpeg, jpg, png and gif remember it wont catch which has gif?blabla

    $bodyText = "The text you want to filter goes here. http://google.com http://s3.buysellads.com/1250418/34135-1282003972.gif";
    function formatUrlsInText($text){
        $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
        preg_match_all($reg_exUrl, $text, $matches);
        $usedPatterns = array();
        foreach($matches[0] as $pattern){
            if(!array_key_exists($pattern, $usedPatterns)){
                $usedPatterns[$pattern]=true;
                // now try to catch last thing in text          
                $pattern2 = substr($pattern, -3);
                if($pattern2 == "gif" || $pattern2 == "peg" || $pattern2 == "jpg" || $pattern2 == "png"){
                    $text = str_replace($pattern, '<img src="'.$pattern.'">', $text);   
                } else {
                    $text = str_replace($pattern, '<a href="'.$pattern.'">'.$pattern.'</a>', $text);
                }   
            }
        }
        return $text;            
    }
    $format = formatUrlsInText($bodyText);
    echo $format;
    
  57. Nestsman
    Permalink to comment#

    Thanks brother. Your code works nicely.

  58. Harisankar P S
    Permalink to comment#

    Just wanted to share how we could do this ruby if anyone is interested.

    "The text you want to filter goes here. http://google.com".
    gsub(/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/) {|s|
    "<a href ='#{s}'>#{s}</a>"
    }

  59. Skyler
    Permalink to comment#

    The regex in the article works, but it also returns match groups, that you likely don’t want, and will muddy up your results. An easy fix for it, is to ignore those match groups with ?:

    eg: (?:http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?

    This will return ONLY the url in a preg_match, and an array of urls in a preg_match_all.

    WIN!

  60. anon
    Permalink to comment#

    @ffsplus2

    How do I go about reusing the $pattern variable more than once for the image? I tried using an echo within the string after assigning say $newurl = $pattern; but it didn’t work. The only alternative I could imagine is to use CSS to add before and after the url to that image. Reason for the url? Fancybox :P

  61. GregR
    Permalink to comment#

    Do any of these do it as we’re typing?

  62. Alexander Griffioen
    Permalink to comment#

    I’m using this:

    function autolink($content)
    {
        $re = '/((?:http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*))?/';    
        $content = preg_replace($re, '<a href="\\1" rel="nofollow">\\1</a>', $content);
        return $content;
    }
    
    
  63. Alexander Griffioen
    Permalink to comment#

    Eh… scratch that. I just noticed it’s adding a gazillion links to every character :/

  64. Damir Calusic
    Permalink to comment#

    This solved my problem :)

    function autolink($content){
        $re = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';    
        $content = preg_replace($re, '<a href="$0" rel="nofollow">$0</a>', $content);
    
        return $content;
    }
    
  65. Andrés Chandía
    Permalink to comment#

    Hi everyone, I have a code that renders a table from mysql, one of the fields is url for which I need the autolink function, I’ve been searching and testing a lot, but I can not find a solution, I would appreciate a lot if somebody could help me, here is my code:

    <?php
    $query = "SELECT * FROM
    values ORDER BY id";
    $result = mysql_query($query);
    if (!$result) {
    die("Query to show fields from table failed");
    }
    $fields_num = mysql_num_fields($result);
    echo "";
    for($i=0; $i<$fields_num; $i++)
    {
    $field = mysql_fetch_field($result);
    echo "".strtr(" {$field->name} ", $transname)."";
    }
    echo "\n";
    while($row = mysql_fetch_row($result))
    {
    echo "";
    foreach($row as $cell)
    echo "$cell";
    echo "\n";
    }
    mysql_free_result($result);
    ?>

  66. Andrés Chandía
    Permalink to comment#

    I better post the complete code again, otherwise is a mess, sorry again:

    <?php
    $query = "SELECT * FROM <code>values</code> ORDER BY <code>id</code>";
    $result = mysql_query($query);
    if (!$result) {
        die("Query to show fields from table failed");
    }
    $fields_num = mysql_num_fields($result);
    echo "<table class='sortable'><tr>";
    for($i=0; $i<$fields_num; $i++)
    {
        $field = mysql_fetch_field($result);
        echo "<td align=center>".strtr(" {$field->name} ", $transname)."</td>";
    }
    echo "</tr>\n";
    while($row = mysql_fetch_row($result))
    {
        echo "<tr onMouseOver=this.bgColor='#e0e0e7'; onMouseOut=this.bgColor='white';>";
        foreach($row as $cell)
            echo "<td align=center>$cell</td>";
        echo "</tr>\n";
    }
    mysql_free_result($result);
    ?>
    
  67. Bjorn
    Permalink to comment#

    What if the text has a mix of tagged URL’s and URL’s which are not tagged?
    E.g. like this:

    https://www.google.com
    
    <a href="https://www.google">https://www.google.com</a>
    

    How can we prevent preg_replace() to pick up the url’s in the second one to avoid them to be replaced by another tag.

  68. Olivier
    Permalink to comment#

    Damir, you got it. Thank you very much.
    Olivier From France

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```