Converting text with link to hyperlink in PHP

by Kishore on September 7, 2008

I wanted to covert http texts in my twitter plugin  to clickable links. I wrote a small function which may be of your use.

<?php
// string with URL's need to be changed to html format adding the the <a> tag

$str1 = "my name is kishore and my web page is http://www.kisaso.com all are welcom 

http://kish.in isPR checker which also display the pagerank of the current page 

with a small image. I am testing http://this.com plugin on my blog and need 

to do some work o";
changeToUrl($str1);
function changeToUrl($str) {
    $flag=true;
    // storing the original text
    $tempStr = $str;
    for($i=0 ; $flag==true; $i++) {

        //Getting the first http position, I checking if any text begins with http, you can 

//modify this according to your need
        $httpos = strpos($tempStr, 'http');
        //checking if any more http available in the text
        if( $httpos === false) $flag=false;
        // Removing the text before the http position
        $afterurl = substr($tempStr, $httpos);
        // Getting the space postion after the url which means the end of the URL
        $gapos = strpos($afterurl, " ");
        // Getting the URL text for which we need to replace with the <a> tag
        $finalurl = substr($afterurl, 0, $gapos);
        // Getting the length of the URL
        $lengthOfUrl = strlen($finalurl);
        //Getting the text removing the URL that is to scan for the next URL    
        $tempStr = substr($afterurl,$lengthOfUrl);
        // This will replace the URL adding the <a> tag
        $replace = '<a href ='.$finalurl.'>'.$finalurl.'</a>';
        // replacing the URL with <a> tag
        $includelink = str_replace($finalurl, $replace, $str);
        // Saving the new string after replacing the URL with <a> tag and goes to the next URL
        $str=$includelink;
    }
    echo $includelink;
}
?>

Possibly Interesting Posts

New Guidelines for Plugin Developers - Wordpress : Mark Jaquith has written on his blog on the Wordpress plugin repository where Plugin Authors can hos..[](0)
Adobe Plugs 13 Security Holes in Critical Update : Adobe Systems embarks on a new schedule for security updates with 13 critical fixes in tow for Reade..[](1)
Security Expert Suggests Twitter Focus on Output Escaping not Input Filtering : Twitter's status blog this morning announced that Twitter has addressed the most recent variant of..[](1)
iPhone Upgrade 3.01 - SMS Vulnerability Fix : You have to update your iPhone with version 3.01. This fixes an SMS vulnerability.The flaw, disclos..[](23)
Fill out your e-mail address to receive our free newsletter from Kishore Blog!
E-mail address:
Name:
 

Leave a Comment

Previous post:

Next post: