Converting URL to clickable link
Using a regex routine, we can find instances of URLs in a block of text and wrap them in <a> elements.
There’s often a need to do some sort of conversion within a chunk of text. Sometimes simple string methods work fine. Other times we need to look to more powerful means. At these times, we pull out the regex docs and go to work.
I had such a need recent.
In the blog here, I use the Twitter Timeline plugin written by Derek Jones to import and display Tweets. For some reason, Derek didn’t handle the conversion of URLs to links. This is an omission, IMO, as all major Twitter widgets available have this feature.
Adding the conversion regex
At approximately line 265, just after the block which changes for “status_relative_date”, add the following:
if ($var_key == 'text')
{
$chunk = $this->statuses[$key]['text'];
/* This is the regex goodness. */
$str = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+
[[:alnum:]/]","<a href=\"\\0\">\\0</a>", $chunk);
/* *********** */
$tagdata = $TMPL->swap_var_single($var_key, $str, $tagdata);
}
This pulls out the “text” portion of the data received from Twitter. It then looks through it for any URLs and wraps the URL in an <a> element.
Comments
No one's commented yet. Add yours!
Add Comment