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);
}
题
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?
解决方案
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);
}
其他提示
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) ;