Howdy,
Today i have interesting and simple PHP tutorial, How to transform string url to html url and i mean how to transform
This -> http://www.something.tld — into this -> http://www.something.tld
it’s very simple using preg_replace function … But actually i find the whole regular expression functions hard to understand and really it’s not human readable…
So let’s start,
<?
class URL_Detector{
private $URL;
public function Detect($string){
$Replace = preg_replace("/(http:\/\/[^\s]+)/i", "<a href=\"$1\">$1</a>", $string);
$this->URL = $Replace;
return $this->URL;
}
}
?>
As you can see i’m using classes to make the detector because classes are very flexible, So let me explain what’s happening up there .
Inside the preg_replace function i’m using this — /(http:\/\/[^\s]+)/i – as the pattern and this just looking for urls starting by http:// so you can’t detect url starting with www .
Then i’m using this – <a href=\”$1\”>$1</a> — as the replacement, but you could ask yourself what does $1 mean?
So $1 refer to the words or the sentence which we want to find and replace and it called reference, and it been there since PHP 4.0.4 , you can replace $ with \\ so we can write it like this – <a href=\”\\1\”>\\1</a> — and it will still work.
Now let’s back to our class,
Let’s test it:
<? $URL = new URL_Detector(); $Text = 'I have 2 websites http://www.zingyso.com/ And http://sru.me and http://www.zingyso.com/b is my blog'; echo $URL->Detect($Text); ?>
The code above should return:
I have 2 websites http://www.zingyso.com/ And http://sru.me and http://www.zingyso.com/b is my blog
—-
And that’s it, now you have String to URL Transformer…
Hope you enjoyed and have a nice day