Img tag src matching PHP regex

耗尽温柔 提交于 2019-12-25 04:22:21

问题


I'm trying to match src="URL" tags like the following:

src="http://3.bp.blogspot.com/-ulEY6FtwbtU/Twye18FlT4I/AAAAAAAAAEE/CHuAAgfQU2Q/s320/DSC_0045.JPG"

Basically, anything that has somre sort of bp.blogspot URL inside of the src attribute. I have the following, but it's only partially working:

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

回答1:


This one accepts all blogspot urls and allows escaped quotes:

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

The URL gets captured to match group 1.

You will need to escape \ and / with an additional \ (for each occurence!) to use in preg_match(…).

Explanation:

src=" # needle 1
( # start of capture group
    (?: # start of anonymous group
        [^"] # non-quote chars
        | # or:
        (?:(?<!\\)(?:\\\\)*\\") # escaped chars
    )+ # end of anonymous group
    \b # 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


来源:https://stackoverflow.com/questions/9122208/img-tag-src-matching-php-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!