小技巧系列:正则匹配img标签

背景:

做论坛之类的一般都会有发帖回帖的功能,那么当用户复制了其他网站的文章的时候,文章的图片就是其他网址的了,这样难保不会有涉及到黄赌毒之类敏感的图片,所以很多时候,只能上传在自己论坛相册的图片会安全点,所以要对复制的站外图片进行过滤。

代码:

$whiteList = [];//网站白名单,当是兄弟网站的时候就不过滤
$pregRule = "/<[img|IMG].*? src=[\'|\"](.*?)[\'|\"].*?[\/]?>/";
preg_match_all($pregRule, $content, $array, PREG_PATTERN_ORDER);
foreach($array[1] as $index => $src){
    $isWai = true;
    foreach($whiteList as $white){
        if(strpos($src,$white) !== false){
            $isWai = false;
            break;
        }
    }
    if ($isWai){
        $content = str_replace($array[0][$index], '<img alt="[外部图片]">', $content);
    }
}
$array[1]的内容是多个src地址;$array[0]是多个img标签的html

有什么不对或有疑问的地方请大佬们指正:):blush:

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 1

那我也贴一个切割url的正则吧,如果有更好的写法请不吝赐教!

匹配url并且分割成不同部分

比如将urlhttps://www.weibo.com/aj/xxx/xxx?a=a&b=b&c=d&df=df#fdfdf切割成以下四部分:

<?php

$str = 'http://www.weibo.com/aj/xxx/xxx?a=a&b=b&c=d&df=df#fdfdf';
// $str = 'https://www.weibo.com/aj/mindpage/sendtail?#adad';
// $str = 'https://www.weibo.com/aj/mindpage/sendtail?a=a&b=b';
// $str = 'https://www.weibo.com';
// $str = 'https://www.weibo.com/';
// $str = 'https://www.weibo.com/?#asd';
// $str = 'http://www.weibo.com?a=a&b=b&c=d&df=df#fdfdf';
// $str = 'http://www.weibo.com/?a=a&b=b&c=d&df=df#fdfdf';
$pattern = '/^(\w+:\/\/[^\/^\?^\#]*)\/?([\w\/]*[^\?]*?)\??(.*?[^#]*)#?(.*?)$/';


preg_match($pattern, $str, $match); 
var_dump($match);
3年前 评论
bestcyt (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!