我使用 preg_match
和模式 $pattern = '/src="http:\/\/(.*?).jpg"/s';
来获取网址网页上的 jpeg 图像。但是,这不够准确,因为它还抓取 http://www.domain.com/image.png"> Yadayada
其他时候,它会抓取类似的东西
http://maps.google.com/maps/api/staticmap?center=42.34,-71.18&path=weight:4|42.338,-71.177|42.338 ,-71.183|42.342,-71.183|42.342,-71.177|42.338,-71.177&zoom=15&size=335x225&sensor=false"宽度=“280”高度=“188”alt=“”> |
我该如何改进防止不必要的匹配(如上面的两个示例)的模式?
I am usng preg_match
with the pattern $pattern = '/src="http:\/\/(.*?).jpg"/s';
to grab urls of jpeg images off a webpage. However, this is not accurate enough as it also grabs http://www.domain.com/image.png"> Yadayada <img src="anotherpic.jpg
.
Other times, it grabs stuff like
http://maps.google.com/maps/api/staticmap?center=42.34,-71.18&path=weight:4|42.338,-71.177|42.338,-71.183|42.342,-71.183|42.342,-71.177|42.338,-71.177&zoom=15&size=335x225&sensor=false" width="280" height="188" alt=""></td></tr> <tr><td height="10"></td></tr></table></td></tr></table></td></tr><tr><td height="10 valign="> </td></tr><tr><td valign="top" background="http://www.coolapartments.info/img/java-footer_bg.jpg
How can I improve the pattern to prevent unwanted matching like the 2 examples above?
发布评论
评论(2)
将
(.*?).jpg
替换为([^"]*)\.jpg
以避免跨越src
属性甚至可以使用src="([^"]*)\.jpg"
更通用,而不匹配http
。Replace the
(.*?).jpg
by([^"]*)\.jpg
to avoid crossing the double quote boundary of thesrc
attribute. It could even be more generic withsrc="([^"]*)\.jpg"
, without matching thehttp
.使用 DOM 和此 XPath
来匹配某处包含字符串“.jpg”的元素的所有 src 属性。
如果属性应以“.jpg”结尾,请使用
相当于 XPath 2.0 函数的结尾。
使用 DOM 和 XPath 的主要好处是它只能对 src 属性进行操作,而您的正则表达式可以在任何地方匹配。这里有大量 DOM 和 XPath 的使用示例:
Use DOM and this XPath
to match all src attributes of elements that contain the string ".jpg" somewhere.
If the attribute should end in ".jpg" use
which is the equivalent to the XPath 2.0 function ends-with.
The main benefit of using DOM and XPath is that it will only operate on src attributes, while your regex matches everywhere. There is plenty of usage examples for DOM and XPath here: