"Hello .. always visit http://cupu-blagu.blogspot.com to get info about PHP programming"
Well .. once submitted, it will automatically text 'http://blog.rosihanari.net' contained in the above string will become a link automatically without our html tags to link <a href="…"> ... </ a> on URL. To more easily, may be more comfortable if I call it with 'auto hyperlink' okay...
If you are using Wordpress, then this hyperlink auto automatically occur on the comment. But, what if we want to make our own auto hyperlink? Well...it's quite easy, so...keep reading this article until the end.
We can make the script auto hyperlink above by using PHP. What about the idea? The idea is the first step we separate or split the original string prior to the substring based on the character of spaces.
For example, suppose there is the following string:
"http://cupu-blagu.blogspot.com site is really cool."
If we split the string into the substring based on a space character, the substring will we get the following:
Substring to-0: http://cupu-blagu.blogspot.com
Substring to-1: site
Substring to-2: is
Substring to-3: really
Substring to-4: cool
Thus, in total there are 5 substring. Then, for each substring, we check that starts with 'http://'. If there substring that begins with 'http://' then the substring will be direplace with
Thus, the result string after replacing process complete is
<a href="http://cupu-blagu.blogspot.com">http://cupu-blagu.blogspot.com</a> site is really cool
Therefore, the replacing process should not be applied to the only pieces of 'http://' substring.
You should understand now. Well ..now we can create the PHP script as the implementation of the ideas above. Here is the script :
// original string$string = "Example some site http://cupu-blagu.blogspot.com and http://";
// splitting process to substring$break = explode(" ", $string);
// replacing processfor ($i=0; $i<=sizeof($break)-1; $i++)
if ((substr($break[$i], 0, 7) == 'http://') && ($break[$i] != 'http://'))
$string = str_replace($break[$i], "<a href='".$break[$i]."'>".$break[$i]."</a>", $string);
The results of the above script looks like below.
Example some site http://cupu-blagu.blogspot.com and http://
Quite easy right? The script above is only a sample script, where the string input not included from a form. Well .. You can modify the script above, so the input string will be included from a form. Just feel free to ask. If you like this tutorial please make a comment here :D