Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

php - Any preg_match() to extract image urls from text?

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.

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

i believe it can be done with preg_match()

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

For example:

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

Or

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...