1

This is the code I currently have. How would I tweak it to include http:// in the href in the returned result every time? Currently, http:// is not in the returned result unless it's in the original string variable $text. I wish to have it added to the href if it is not in the original $text. Thanks!

function urlfixer($text){

   $pattern  = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
   $callback = create_function('$matches', '
       $url       = array_shift($matches);
       $url_parts = parse_url($url);

       $text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
       $text = preg_replace("/^www./", "", $text);

       $last = -(strlen(strrchr($text, "/"))) + 1;
       if ($last < 0) {
           $text = substr($text, 0, $last) . "&hellip;";
       }

       return sprintf(\'<a rel="nofollow" href="%s">%s</a>\', $url, $text);
   ');

   return preg_replace_callback($pattern, $callback, $text);
}
1
  • You can't just append it to the beginning when you return from the your function? Commented Mar 28, 2013 at 3:15

2 Answers 2

2

Since you don't know if your $url has http:// on it or not just stick it on the beginning, and then make sure it's stripped just in case.

$url = 'http://' . str_replace('http://','',$url);
return sprintf('<a rel="nofollow" href="%s">%s</a>', $url, $text);
Sign up to request clarification or add additional context in comments.

1 Comment

I like the simplicity of this approach but it's probably a bit safer to only replace occurrences of http:// at the start of the string.
1
$url       = array_shift($matches);
if( substr($url,0,6)!='http://' ) {
    $url='http://'.$url;
}

something like this should do it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.