正则表达式模式以匹配来自文本的图像URL

时间:2012-10-17 11:43:56

标签: regex

我正在使用此正则表达式,但不匹配url与子域名。

(https?://[^\s]+(?=\.(jpe?g|png|gif))).(jpe?g|png|gif)

匹配:http://domain.com/folder1/folder2/folder3/image.jpg

不匹配:http://sub.domain.com/folder1/folder2/folder3/image.jpg

2 个答案:

答案 0 :(得分:1)

此正则表达式匹配JPG,PNG和GIF图像的格式正确的网址(包括具有子域名,端口号和查询字符串的网址):

((?:https?\:\/\/)(?:[a-zA-Z]{1}(?:[\w\-]+\.)+(?:[\w]{2,5}))(?:\:[\d]{1,5})?\/(?:[^\s\/]+\/)*(?:[^\s]+\.(?:jpe?g|gif|png))(?:\?\w+=\w+(?:&\w+=\w+)*)?)

PHP示例:

<?php

$str = 'Lorem ipsum http://example.com/img.jpg dolor sit http://www.aaa.cc/this/is/not/an/image.html amet, consectetur http://my.domain.com/path/to/nothing.gif adipiscing elit http://www.imgbucket.com/some/other/image.png';

preg_match_all('@((?:https?\:\/\/)(?:[a-zA-Z]{1}(?:[\w\-]+\.)+(?:[\w]{2,5}))(?:\:[\d]{1,5})?\/(?:[^\s\/]+\/)*(?:[^\s]+\.(?:jpe?g|gif|png))(?:\?\w+=\w+(?:&\w+=\w+)*)?)@', $str, $matches);

print_r($matches[1]);

输出:

Array
(
    [0] => http://example.com/img.jpg
    [1] => http://my.domain.com/path/to/nothing.gif
    [2] => http://www.imgbucket.com/some/other/image.png
)

答案 1 :(得分:-1)

https?://\w+\.\w+/\S+\.(jpe?g|png|gif)

在第一个/之前只匹配一个点。

\S[^\s]相同,只是更短。