Reputation: 209
I'm building a simple blog script that allows the users to put html in the content (I'm using htmlpurifier). I want the users to be able to post image urls, but only from imgur. How can I best approach this method using preg_match and str_replace?
Example. If image url is not from imgur then use str_replace and delete it.
After playing around with DOMDocument (Jack adviced on the chat to use DOM instead) I came up with the solution to my own question.
// 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;
}
}
Upvotes: 1
Views: 150
Reputation: 173642
Assuming you have the URL:
$host = parse_url($url, PHP_URL_HOST);
$suffix = 'imgur.com';
if (substr_compare($host, $suffix, -strlen($suffix)) != 0) {
// not an imgur.com link
}
Upvotes: 1