我需要 preg_match()
语法或类似提取 JPG 或 PNG 或 GIF 的语法来自混合文本的URL并将它们放在一个数组中或最后存储第一个URL。
也许是一些搜索以http开头并以jpg / png / gif结尾的字符串的语法。
我相信可以使用 preg_match()
注意:文字可以是这样的: blablablabla“http://www.example.com/xxx.jpg”blablablabla
答案 0 :(得分:12)
请注意他们可以欺骗您的服务器插入假火柴的特殊场合。
例如:
http://www.myserver.com/virus.exe?fakeParam=.jpg
或者
http://www.myserver.com/virus.exe#fakeParam=.jpg
我已经快速修改了正则表达式以避免这种情况,但我很确定可能会有更多(例如,在文件路径中插入%00,并且无法通过正则表达式轻松解析)< / p>
$matches = array();
preg_match_all('!http://[^?#]+\.(?:jpe?g|png|gif)!Ui' , $string , $matches);
因此,为了安全起见,请以最严格的方式使用regex,例如,如果您知道服务器,将其写入正则表达式,或者您知道路径始终包含字母,连字符,点,斜线和数字,使用一个表达式:
$matches = array();
preg_match_all('!http://[a-z0-9\-\.\/]+\.(?:jpe?g|png|gif)!Ui' , $string , $matches);
这应避免将来出现任何有趣的惊喜。
答案 1 :(得分:5)
$matches = array();
preg_match_all('!http://.+\.(?:jpe?g|png|gif)!Ui' , $string , $matches);
答案 2 :(得分:1)
有前缀http / https可选的案例更新,例如:
http://example.com/image.jpg
https://example.com/image.jpg
//example.com/image.jpg
function extractImageUrlFromText($text)
{
preg_match_all('!(https?:)?//\S+\.(?:jpe?g|jpg|png|gif)!Ui', $text, $matches);
return $$matches[0];
}