I created a PHP function that will automatically turn URLs into links, link Twitter @reply usernames to its Twitter profile, and turn email addresses into links with the mailto protocol.
Here is the script:
function autolink($a, $b){
$e = "";
$f = array(
'link' => '~(http(s|)\:\/\/(www\.|)((\w+)\.(\w+)(\:[0-9]{2,5}|)\.[a-z]{2,5}|(\w+)(\:[0-9]{2,5}|)\.[a-z]{2,5}))((((\/|)\w+)(\.[a-z]{2,5}|))+)(\?(\w+\=\w+(\&|))+|)~',
'email' => '~\w+\@\w+(\:[0-9]{2,5}|)\.[a-z]{2,5}~',
'twitter' => '~\@([a-zA-Z_0-9]){1,15}~'
);
switch ($b) {
case "link":$e = preg_replace_callback($f['link'], function ($a) {return '<a href="'.$a.'" rel="nofollow" target="_blank">'.$a.'</a>';},$a);break;
case "email":$e = preg_replace_callback($f['email'], function ($a) {return '<a href="mailto:'.$a.'" rel="nofollow" target="_blank">'.$a.'</a>';},$a);break;
case "twitter":$e = preg_replace_callback($f['twitter'], function ($a) {return '<a href="https://twitter.com/#!/'.str_replace('@','',$a).'" rel="nofollow" target="_blank">'.$a.'</a>';},$a);break;
}
return $e;
}
The only issue I’m having is that instead of returning the link it returns the word: “Array”.
For example, this:
autolink("This is my site http://weebuild.biz", "link");
Is returning this:
This is my site Array
When it should be returning this:
This is my site
<a href="http://weebuild.biz" rel="nofollow"
target="_blank">http://weebuild.biz</a>
The original script was in JavaSript which I wrote as well: http://jsfiddle.net/shawn31313/umgqR/2/
Since I’m not a PHP developer the JavaScript version has some more features.
Maybe the issue is that I took the regular expression from JavaScript and just put it in the PHP. I’m not sure if regular expressions in PHP are different from JavaScript.
Thanks in advance.
Try the following change:
The issue is that the argument to the callback will be an array, not a string.
From the docs: