doublel83422 2014-12-07 08:58
浏览 10
已采纳

当src不在示例域上时,Preg替换所有img

I have a problem with preg_replace, my function have some bug and i dont know where. I need to remove from array every image that has source other than my main domain.

This is my function:

$aPatterns = array (
(...),
'#<img[^>]+src="(?!http://example.com/emoticon/(example|emot|name).gif)[^\s]+"[^>]+>#is',
(...));

$aReplecements = array(
(...),
'',
(...)
);

$contentOut = preg_replace($aPatterns,$aReplecements,$content);

If img tag is not closed or does not have double quotes sign at the end of src attribute function not working, no change to empty string.

I have no idea what is wrong in this expression, I hope, and I count on your help.

Regards,

  • 写回答

1条回答 默认 最新

  • dpfz27768 2014-12-07 09:38
    关注

    Okay, so the problem is that you have explicitly stated that there should be a " and > at the end of the URL (you've also explicitly stated that there should be an opening " at the beginning of the URL after the src= so if that wasn't there it wouldn't work either).

    You can fix this behaviour by making the " and > optional by adding a ? mark after them.

    #<img[^>]+src="?(?!http://example.com/emoticon/(example|emot|name).gif)[^\s]+"?[^>]+>?#is
    

    Note I added a ? after the first " at the beginning of the pattern as well.

    Warning

    Doing this comes with its own problems, for example: [^>] will match any character that isn't a > so could potentially match to the end of the string and therefore you could potentially lose all of the rest of the string from your output (depending on your replacements etc.)...

    Is there any reason why a > wouldn't be present?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?