Img与PHP正则表达式匹配的标记源

2022-03-29 00:00:00 regex php preg-match

我正在尝试匹配src="url"标记,如下所示:

src="http://3.bp.blogspot.com/-ulEY6FtwbtU/Twye18FlT4I/AAAAAAAAAEE/CHuAAgfQU2Q/s320/DSC_0045.JPG"
基本上,任何在src属性中具有某种bp.blogpot URL的内容。我有以下功能,但它只起了部分作用:

preg_match('/src="(.*)blogspot(.*)"/', $content, $matches);

解决方案

此URL接受所有BlokSpot URL并允许转义引号:

src="((?:[^"]|(?:(?<!\)(?:\\)*\"))+blogspot.com/(?:[^"]|(?:(?<!\)(?:\\)*\"))+)"

捕获URL以匹配组%1。

您将需要使用额外的转义/(每次出现!)要在preg_match(…)中使用。

解释:

src=" # needle 1
( # start of capture group
    (?: # start of anonymous group
        [^"] # non-quote chars
        | # or:
        (?:(?<!\)(?:\\)*\") # escaped chars
    )+ # end of anonymous group
     # start of word (word boundary)
    blogspot.com/ # needle 2
    (?: # start of anonymous group
        [^"] # non-quote chars
        | # or:
        (?:(?<!\)(?:\\)*\") # escaped chars
    )+ # end of anonymous group
    ) # end of capture group
" # needle 3

相关文章