首页 > 解决方案 > 尝试使用 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

标签: php

解决方案


您的正则表达式匹配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]+)).*

请注意,前瞻不是捕获组的一部分。

更多详细信息可在此处获得。


推荐阅读