PHP – Cheesy Little PHP Script

Posted on February 5, 2013

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

Leave a Comment

If you would like to make a comment, please fill out the form below.

You must be logged in to post a comment.

© Copyright Jeff's Blog • Powered by Wordpress • Using Detour theme created by Brian Gardner.