是否有任何preg_match()可以从文本中提取图像网址? [英] Any preg_match() to extract image urls from text?

查看:66
本文介绍了是否有任何preg_match()可以从文本中提取图像网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要 preg_match() 语法或类似的东西来从中提取 JPG PNG GIF URL混合文本,然后将它们放入数组中,或者最后存储第一个URL.

i need a preg_match() syntax or something similar to extract JPG or PNG or GIF URLs from a mixed text and put them in an array or at last store the first url.

也许是某些语法,用于搜索以http开头,以jpg/png/gif结尾的字符串.

maybe some syntax which searchs for strings that are beginning with http and ending with jpg/png/gif..

我相信可以通过 preg_match()

i believe it can be done with preg_match()

注意:文字可以是这样的: blablablabla" http://www.example .com/xxx.jpg "blablablabla

Note: the text can be like that : blablablabla"http://www.example.com/xxx.jpg"blablablabla

推荐答案

请注意在特殊情况下,他们可能愚弄您的服务器插入假匹配项.

Please note the special occasions where they can fool your server inserting fake matches.

例如:

http://www.myserver.com/virus.exe?fakeParam=.jpg

http://www.myserver.com/virus.exe#fakeParam=.jpg

为了避免这种情况,我已经快速修改了正则表达式,但是我很确定还会有更多(例如,在文件的路径中插入%00,并且不能由正则表达式轻松解析)

I've modified quickly the regex to avoid this cases, but i'm pretty sure there could be more (like inserting %00 in the path of the file, for example, and cannot be easily parsed by a regex)

$matches = array();
preg_match_all('!http://[^?#]+\.(?:jpe?g|png|gif)!Ui' , $string , $matches);

因此,为了安全起见,请始终以最严格的方式使用正则表达式,例如,如果您知道服务器,请将其写入正则表达式,或者如果您知道路径始终包含字母,连字符,点,斜杠和数字,请使用一个表达式,例如:

So, for security, use always regex in the most restrictive way, for example, if you know the server, write it into the regex, or if you know that the path always will include letters, hyphens, dots, slashes and numbers, use one expression like:

$matches = array();
preg_match_all('!http://[a-z0-9\-\.\/]+\.(?:jpe?g|png|gif)!Ui' , $string , $matches);

这应该避免将来出现任何有趣的惊喜.

This should avoid any funny surprise in the future.

这篇关于是否有任何preg_match()可以从文本中提取图像网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆