0

我有以下变量:

$text = 'This is a sentence [url=http://site.com] that contains urls [url=javascript:alert();]';

以及验证 URL 的以下代码行:

$text = preg_replace('/\[url=([^\\]]+)]/', filter_var('$1', FILTER_VALIDATE_URL), $text);

输出:

“这是一个包含 url 的句子”

如何获得以下输出?

“这是一个包含 url的句子http://site.com ”

4

2 回答 2

2
$text = 'This is a sentence [url=http://site.com] that contains urls [url=javascript:alert();]';
$text = preg_replace_callback(
    '/\[url=([^\\]]+)]/',
    function ($url) {
        $clean = filter_var($url[1], FILTER_VALIDATE_URL);
        if ($clean) {
            return '<a href="' . $clean . '">' . $clean . '</a>';
        } else {
            return "";
        }
    },
    $text
);

http://codepad.viper-7.com/Hwgq90

于 2013-01-26T14:13:26.613 回答
1
<?php

$text = 'This is a sentence [url=http://site.com] that contains urls [url=javascript:alert();]';


function url($url){
    if(filter_var($url, FILTER_VALIDATE_URL))
        return $url;
    return '';
}


$text = preg_replace('/\[url=([^\\]]+)]/e', 'url("$1")', $text);


echo $text;
于 2013-01-26T14:16:25.600 回答