How to hyperlink web addresses

Discussion in 'PHP' started by Gravereaper, Mar 18, 2007.

  1. #1
    <?php
    include("header.php");
    echo "</BR></BR></BR></BR></BR></BR></BR></BR>";
    echo "<div style='position:absolute; overflow:hidden; left:306px; top:172px; width:335px; height:39px; z-index:0'>
    <FONT style='font-size:10pt' color=#000000 face='Tahoma'>
    <DIV><FONT style='font-size:18pt' color=#D0C85E>Some text!</FONT></DIV>
    </FONT>
    </DIV></BR></BR>";
    echo "<FONT style='font-size:10pt' color=666699 face='Comic Sans MS'>";
    $filename = "file1.txt";
    $fo = fopen($filename,"r");
    $contents = fread($fo,filesize($filename));
    echo stripslashes($contents);
    ?>
    Code (markup):
    How can i hyperlink any websites with http:// protocol, i.e. a site link is placed between other text in $contents, and i want to make it a hyperlink when the $contents are echoed in a HTML file.

    $contents = some text here http://www.somewebhere.com some text here
    echo $contents
    
    Code (markup):
    Now what should i add so that the site becomes a hyperlink when printed on the html page.

    Thanks
     
    Gravereaper, Mar 18, 2007 IP
  2. cbn81

    cbn81 Peon

    Messages:
    160
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You should add to http:// the html tag <a, it should be <a href="http://www.yoursite.com">http://www.yoursite.com</a>, so you should look for a word that begins with http:// and replace it with the code above...
     
    cbn81, Mar 18, 2007 IP
  3. Gravereaper

    Gravereaper Banned

    Messages:
    450
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You just rephrased my question :p, thats exactly what i am asking. How!
     
    Gravereaper, Mar 18, 2007 IP
  4. m0nkeymafia

    m0nkeymafia Well-Known Member

    Messages:
    399
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    125
    #4
    You want to use some kind of regular expression match

    Look at this link, its the php preg_replace function and the comment I linked you to provides all the code you need!

    In case your lazy here it is ;)

    <?php
    $text="I like http://www.yahoo.com, http://www.google.com, and I connect through FTP to my site through ftp://www.mysite.com.";
    
    function url_links($string)
    {
    $string=preg_replace("/(http:\/\/|ftp:\/\/)([^\s,]*)/i","<a href='$1$2'>$1$2</a>",$string);
    return $string;
    }
    
    print url_links($text);
    ?>
    Code (markup):
     
    m0nkeymafia, Mar 18, 2007 IP
    Gravereaper likes this.
  5. Gravereaper

    Gravereaper Banned

    Messages:
    450
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #5
    It worked for me thanks, rep added! ;)
     
    Gravereaper, Mar 18, 2007 IP