Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a bbCode function I made:

function bbCode($str)
{
    $values = array(
      '@\[link="(.*?)"\](.*?)\[\/link\]@i' => '<a href="$1">$2</a>'

    );
    return preg_replace(array_keys($values), array_values($values), $str);
}

It works well but if the user types, for example [link="google.com"]Something[/link], the result would be

<a href="google.com">Something</a>

And that would return to www.mywebsite.com/google.com How could I prevent this from happening?

share|improve this question
2  
Why not use PHP.net/bbcode? – shiplu.mokadd.im Jun 20 at 9:38

2 Answers

up vote 0 down vote accepted

You can prefix it with http://

function bbCode($str)
{
$values = array(
  '@\[link="[http:\/\/]*(.*?)"\](.*?)\[\/link\]@i' => '<a href="http://$1">$2</a>'
);
return preg_replace(array_keys($values), array_values($values), $str);
}
share|improve this answer
What if the user types ht'tp://google'.com, that would return ht'tp://ht'tp://google'.com – John Balls Jun 20 at 9:38
try my updated code – DevZer0 Jun 20 at 9:41
Doesn't work, it redirects me to http// – John Balls Jun 20 at 9:43
try now i update the regexp – DevZer0 Jun 20 at 9:48

I think you should check for a valid URL this way:

function bbCode($str)
{   
    $new = preg_replace_callback('@\[link="(.*?)"\](.*?)\[\/link\]@i', function($matches){
        $url = $matches[1] ;
        $text = $matches[2] ;

        if (filter_var($url, FILTER_VALIDATE_URL) === FALSE){
            $url = "http://{$url}" ;
        }

        return "<a href='{$url}'>{$text}</a>" ;
    }, $str);

    return $new ;
}


$code = '[link="google.com"]TEXT[/link]' ;
echo bbCode($code) ;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.