php - 尝试使用 preg_match_all 匹配所有包含特定类的图像
问题描述
preg_match_all
我尝试使用该函数匹配包含特定类的所有图像。
这是我与内容中的所有图像匹配的旧代码:
preg_match_all( '/<img[\s\r\n]+.*?>/is', $content, $matches );
这是我尝试制作的代码以匹配只有特定类但我失败的图像:
preg_match_all( "/(<img((?!(.*?)class=['\"](.*?)comment-media(.*?)['\"](.*?)).)*>)+/is", $content, $matches );
我需要搜索的类是:comment-media
解决方案
您的正则表达式匹配img
没有comment-media
该类的每个标签。Regex101将此部分列为“Negative Lookahead”:
(?!(.*?)class=['\"](.*?)comment-media(.*?)['\"](.*?))
你需要删除那个负面的lookahead。
生成的正则表达式将是:
(<img(.*class=['\"](.*)comment-media(.*)['\"].*)*>)+
在此处查看实际操作:https ://regex101.com/r/yh7dqj/1
什么是负前瞻?
负前瞻用于匹配未跟随其他内容的内容。它总是以(?!
. 例如,要匹配foo
后面没有的字符串bar
,可以使用:
foo(?!bar)
要匹配foobar
后面不跟数字的,可以使用:
# Notice the parenthesis around the part of the negative lookahead. You'll need these to use lookaheads with regex expressions.
foobar(?!([0-9]+)).*
请注意,前瞻不是捕获组的一部分。
更多详细信息可在此处获得。
推荐阅读
- python - Lambda 表达式 (Python)
- html - 如何让我隐藏的 div 显示在下拉菜单中
- mysql - 检索 MySQL 中不具有 NULL 或特定值的属性
- javascript - 如何在 Discord.js 中获得角色?
- c++ - 这个声明真的改变了错误所说的意思吗?
- c - 非常量变量的正确术语
- php - 类 Illuminate\Validation\Rules\RequiredIf 的对象无法转换为 int
- google-colaboratory - Colab pro 改进和用户反馈
- java - 使用 ${} 的 log4j 属性中的 Weblogic 12 相对路径不起作用
- extjs - ExtJS 无法读取 null 的属性“addClass”