2014-10-12 29 views
0

我想从html源代码使用以下正则表达式的图像网址,但它失败时,图像的网址中有空格。例如,这个网址:preg_match_all正则表达式失败时,有空格

<img src="http://a57.foxnews.com/global.fncstatic.com/static/managed/img/Entertainment/876/493/kazantsev pink bikini reuters.jpg?ve=1&amp;tl=1" alt="kazantsev pink bikini reuters.jpg" itemprop="image"> 

$image_regex_src_url = '/<img[^>]*'.'src=[\"|\'](.*)[\"|\']/Ui'; 
preg_match_all($image_regex_src_url, $string, $out, PREG_PATTERN_ORDER); 

这让我回到以下。
http://a57.foxnews.com/global.fncstatic.com/static/managed/img/Entertainment/876/493/kazantsev

有没有办法匹配任何字符,包括空格?或者是我必须在php配置中设置的东西?

+0

'。*'也包含空格。问题不在这里,正则表达式工作正常。显示您正在尝试应用的文字。这可能会发生,没有空格,但'''或'''(他们不应该在URL中) – Cheery 2014-10-12 00:18:11

+0

你可以简化你的正则表达式:' 2014-10-12 00:31:56

+0

I'm trying to post the string here to see if there's some other reason it won't work, but I'm having trouble with stackoverflow truncating it, is there a tag I can put in the comments when pasting in code? kazantsev pink bikini reuters.jpg techdog 2014-10-12 00:50:18

回答

1

您的正则表达式有几个问题。

首先,您尝试使用连接运算符('.')将表达式的两个部分连接在一起(,这不是必需的)。其次,你不需要在你的角色类中使用替换运算符|

.将匹配除换行符之外的任何字符。这些标签可能包含换行符,因为它们位于HTML源代码中。您可以使用s(dotall)修饰符,该修饰符强制该点匹配包括换行符在内的任何字符,或使用否定字符类,意思是匹配除之外的任何字符

使用sDOTALL)修改器:

$image_regex_src_url = '/<img[^>]*src=(["\'])(.*?)\1/si'; 

使用否定的字符类[^ ]

$image_regex_src_url = '/<img[^>]*src=(["\'])([^"\']*)\1/i'; 

虽然,它是非常容易使用的解析器,例如DOM抢结果。

$doc = new DOMDocument; 
@$doc->loadHTML($html); // load the HTML 

foreach($doc->getElementsByTagName('img') as $node) { 
    $urls[] = $node->getAttribute('src'); 
} 

print_r($urls); 
+0

这更好,我会尝试后我修复了第一个问题,谢谢 – techdog 2014-10-12 00:52:08

+0

感谢您为清理正则表达式以及替代方法,这个方法更加简洁和可能更快,并且非常感谢您的理解,以供将来参考,如何将s( dotall)modifier – techdog 2014-10-12 01:15:57

+0

再次感谢,我将用你建议的dom解决方案重新编写代码。 – techdog 2014-10-12 01:23:26