Finding urls and making them hyperlinks

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • laredotornado@zipmail.com

    Finding urls and making them hyperlinks

    Hello,

    I want to take a block of text and add html tags to make hyperlinks
    where hyperlink strings exist. So, if I have a variable

    $a = "This is http://www.yahoo.com"

    I would like to run that through a function such that the value of $a
    is

    "This is <a href='http://www.yahoo.com'> http://www.yahoo.com</a>"

    How can I do this? Any help is greatly appreciated. I am using PHP 4.

    Thanks, - Dave

  • John McClumpha

    #2
    Re: Finding urls and making them hyperlinks

    On 19 Nov 2005 13:39:46 -0800, laredotornado@z ipmail.com wrote:[color=blue]
    >I want to take a block of text and add html tags to make hyperlinks
    >where hyperlink strings exist. So, if I have a variable
    >
    >$a = "This is http://www.yahoo.com"
    >
    >I would like to run that through a function such that the value of $a
    >is
    >
    >"This is <a href='http://www.yahoo.com'> http://www.yahoo.com</a>"[/color]

    making the following 2 assumptions:

    URL begins with " http" (and there is only one instance within $a)
    URL contains no spaces

    something like the following (untested) code should work - (this can
    most likely be optimized and I'd be interested to know how if anyone
    can help out):

    <?

    $a = "This is http://www.yahoo.com";

    // break everything to the left of "http"
    $MyURL = substr($a, strpos($a, "http"));
    $MyIntro = substr($a, 0, strpos($a, "http"));

    // remove anything after URL (if existing)
    if (strpos($MyURL, " ")) { // there is a space in the string (after
    URL)
    $MyURL = substr($MyURL, 0, strpos($MyURL, " "));
    }

    $MyOutput = $MyIntro . "<a href=\"" . $MyURL . "\">" . $MyURL .
    "</a>";

    echo $MyOutput;
    ?>


    --
    John McClumpha
    Darkness Reigns - http://www.incitegraphics.com.au/darkness/

    Comment

    • Chung Leong

      #3
      Re: Finding urls and making them hyperlinks

      Something like this should do the trick:

      $a = preg_replace('/(http:\S+)/', '<a href="\1">\1</a>', $a);

      Comment

      Working...