PHP – Cheesy Little PHP Script

Programming,Snippets — Jeff Eske on February 5, 2013 at 4:04 pm

Here’s a cheesy little script that parses a block of text and “linkifies” URLs.  It basically breaks the text into individual “words” and stores them in an array.  It then checks each array element to see if it appears to be a web address.  If it appears to be, it encloses address in the appropriate link code, so that it will be clickable.  If not, it simply spits it back as-is.

[code]

<?php

$content = “This is some test content.”;
#### Parse content for URLs ####
$shrapnel = explode(” “,$content); // break the text string into pieces and place them in an array.
$total = count($shrapnel); // count the pieces of shrapnel
for($i=0;$i<=$total;$i++){ // step through the array, looking at the pieces to see if they start with http
if(preg_match(“/^http./”, $shrapnel[$i])){
echo”<a href=’$shrapnel[$i]’>$shrapnel[$i]</a> “;
}
else{
echo”$shrapnel[$i] “;
}
}
?>

[/code]

You could also add a regexp for “www”, if you wanted to catch websites that don’t include the http or https.  Obviously, this has no error handling or anything else included.  It came in handy in a particular situation, so I decided to post it.

Jeff Eske

0 Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

You must be logged in to post a comment.

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. | Jeff's Blog