Pregunta

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.

¿Fue útil?

Solución

Try the following change:

case "link":$e = preg_replace_callback(
        $f['link'],
        function ($a) {
            return '<a href="'.$a[0].'" rel="nofollow" target="_blank">'.$a[0].'</a>';
        },
        $a
     );
     break;

The issue is that the argument to the callback will be an array, not a string.

From the docs:

A callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string.

Otros consejos

The $a inside of the callback is an array and returns something like this:

Array
(
  [0] => http://weebuild.biz
  [1] => http://weebuild.bi
  [2] => 
  [3] => 
  [4] => weebuild.bi
  [5] => 
  [6] => 
  [7] => 
  [8] => weebuild
  [9] => 
  [10] => z
  [11] => z
  [12] => z
  [13] => 
  [14] => 
  [15] => 

)

You might want to refer to $a[0] instead of just $a. Of course you need to do some checks to make sure there's that value and avoid any unexpected errors when referring to it.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top