【问题标题】:PHP - Using preg_replace to put http:// before linkPHP - 使用 preg_replace 将 http:// 放在链接之前
【发布时间】:2013-06-17 02:37:22
【问题描述】:

我做了一个bbCode函数:

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

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

它运作良好,但如果用户键入,例如 [link="google.com"]Something[/link],结果将是

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

然后返回到 www.mywebsite.com/google.com 我怎样才能防止这种情况发生?

【问题讨论】:

  • 为什么不使用 PHP.net/bbcode?​​span>

标签: php preg-replace bbcode


【解决方案1】:

我认为您应该这样检查有效的 URL:

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) ;

【讨论】:

    【解决方案2】:

    你可以在它前面加上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);
    }
    

    【讨论】:

    • 如果用户输入 ht'tp://google'.com 会返回 ht'tp://ht'tp://google'.com
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多