使用preg_match和str_replace验证链接


Using preg_match and str_replace to verify link

我正在构建一个简单的博客脚本,允许用户在内容中放入html(我使用的是html净化器)。我希望用户能够发布图片url,但只能从imgur发布。如何使用preg_match和str_replace来最好地处理此方法?

示例。如果图像url不是来自imgur,则使用str_replace并将其删除。


在玩了DOMDocument之后(Jack在聊天中建议使用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;
    }
}

假设您有URL:

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