2013-08-02 75 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 
}