2013-08-02 73 views
1

我正在构建一个简单的博客脚本,它允许用户将html放入内容中(我正在使用htmlpurifier)。我希望用户能够发布图片网址,但只能从imgur发布。如何使用preg_match和str_replace最好地处理此方法?使用preg_match和str_replace验证链接

例子。如果图像url不是imgur,请使用str_replace并将其删除。


玩弄DOM文档后(杰克劝聊天使用DOM来代替),我想出了解决我自己的问题。

// let's pretend <img src="" /> is inside content 
$content = $_POST['content']; 

$doc = new DOMDocument; 
libxml_use_internal_errors(true); 
$doc->loadHTML($content); 
libxml_clear_errors(); 

foreach ($doc->getElementsByTagName('img') as $img) { 
    if (parse_url($img->getAttribute('src'), PHP_URL_HOST) != 'i.imgur.com') { 
    $content = preg_replace("/<img[^>]+\>/i", "(invalid image provider) ", $content); 
    echo $content; 
    } else { 
     echo $content; 
    } 
} 
+2

你有没有在这个尚未作出任何企图?如果是这样,请显示它。 – Daedalus

+0

检查这个http://stackoverflow.com/questions/2143202/any-preg-match-to-extract-image-urls-from-text – cartina

+0

会这样的工作吗if(!preg_match('/ http: \/\/i \ .imgur \ .com \ [^&] + /',$ url)){$ err ='无效'; } –

回答

1

假设你有网址:

$host = parse_url($url, PHP_URL_HOST); 
$suffix = 'imgur.com'; 
if (substr_compare($host, $suffix, -strlen($suffix)) != 0) { 
    // not an imgur.com link 
}