changing text to link

Discussion in 'PHP' started by Cinta April, May 24, 2008.

  1. #1
    Hi how do i change a uesr input like

    check out:
    www.example.com

    into a link and still keep all the texts unchanged?
     
    Cinta April, May 24, 2008 IP
  2. NatalicWolf

    NatalicWolf Peon

    Messages:
    262
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You must use regular expressions. Google for it or wait till someone get sit.
     
    NatalicWolf, May 24, 2008 IP
  3. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #3
    
    <?php
    function replace_urls_with_links( $text )
    {
    	return preg_replace(
    		'~(https?://.[^\s]+)~',
    		'<a href="$1" target="_blank">$1</a>',
    		$text
    	);
    }
    
    $document =<<< EOD
    	My document starts with normal text,
    	I go on to post a link to http://interviolet.com
    	I then explain that this is my home page, not like 
    	http://google.com which is a search engine.
    	There are many websites on earth and my aim in life is
    	to take over them all ... starting with http://thefirstsite.com
    EOD;
    
    echo replace_urls_with_links( $document );
    ?>
    PHP:
     
    krakjoe, May 25, 2008 IP
  4. Cinta April

    Cinta April Banned

    Messages:
    262
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    hey thanks krakjoe. however the code doesn't work when somen types www.example.com without the http://.
    i need something that will work when someone includes or doesn't include the http.
     
    Cinta April, May 25, 2008 IP