Changing URL to link with PHP

Writing and publishing text is one of the main activities people do while browsing content on the net. While contributing a website visitors may include links in their submission. When the content is displayed links in the text do not automatically turn into clickable links thus decreasing the usability of the site. Programmers can easily convert dummy URL addresses into links in PHP scrips with a simple preg_replace() function call. The following code snippet shows an example.

$s = 'http://mattimattila.fi'; $s = preg_replace('/([w]+://[w-?&;#~=./@]+[w/])/i', '<a href="$1">$1</a>', $s);

With complex regular expressions you can convert virtually anything in a string. Handy preg_replace() function is very powerful tool and much faster than deprecated old ereg_replace() function. As of PHP 5.3 and 6.0 this outdated function will no longer be supported.

Julkaistu lauantaina 30.1.2010 klo 9:40 avainsanoilla Internet ja ohjelmointi.

Edellinen
Holmes ratkaisee
Seuraava
Lumituiskun jälkeen