我得到了这两个片段:
<a rel="nofollow" href="http://www.amazon.de/gp/product/B004DI7A5S/ref=as_li_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=B004DI7A5S&linkCode=as2&tag=webbigode-21">PFIFF Reitstrumpf kariert, grau/lila, 37-39, 100322-144-37</a><img src="http://ir-de.amazon-adsystem.com/e/ir?t=webbigode-21&l=as2&o=3&a=B004DI7A5S" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />第二个:
<a rel="nofollow" href="http://www.amazon.de/gp/product/B004DI7A5S/ref=as_li_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=B004DI7A5S&linkCode=as2&tag=webbigode-21"><img border="0" src="http://ws-eu.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=B004DI7A5S&Format=_SL110_&ID=AsinImage&MarketPlace=DE&ServiceVersion=20070822&WS=1&tag=webbigode-21" ></a><img src="http://ir-de.amazon-adsystem.com/e/ir?t=webbigode-21&l=as2&o=3&a=B004DI7A5S" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />(请注意,它们是相似的,但第二个稍长一些。)
在第一个片段中,我需要href的内容,在第二个片段中,我需要Image-Source的内容。
这不起作用:
$result = preg_match_all("/<img.*?src\s*=.*?>/",$_POST['bild'],$matches); 我该怎么办?
发布于 2016-05-17 00:50:21
您可以使用Simple HTML DOM来解析RegEx,而不是使用HTML.
include 'simple_html_dom.php';
$html = str_get_html('<a rel="nofollow" href="http://www.amazon.de/gp/product/B004DI7A5S/ref=as_li_tl?ie=UTF8&camp=1638&creative=6742&creativeASIN=B004DI7A5S&linkCode=as2&tag=webbigode-21"><img border="0" src="http://ws-eu.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=B004DI7A5S&Format=_SL110_&ID=AsinImage&MarketPlace=DE&ServiceVersion=20070822&WS=1&tag=webbigode-21" ></a><img src="http://ir-de.amazon-adsystem.com/e/ir?t=webbigode-21&l=as2&o=3&a=B004DI7A5S" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />');
echo $html->find('a', 0)->href . PHP_EOL;
echo $html->find('img', 0)->src;发布于 2016-05-17 00:55:08
这一步提取href (大约36步):
<a(?:\s*(?!href)[^\s>]*)*\s*href=["']([^"']+)这一步提取src (~59步):
<img(?:\s*(?!src)[^\s>]*)*\s*src=["']([^"']+)标签是常规的,可以很容易地被正则表达式解析。注意,我假设属性(href和src)用引号括起来。
这些正则表达式非常快(它们比其他正则表达式快10倍以上)。事实上,考虑到PCRE中的所有优化,它们可能比完整的解析器更快。
本质上,我的正则表达式几乎是相同的。他们找到标记<a的开头,并查看它后面是否有任何属性。如果属性不是您想要的属性,则跳过(?:\s*(?!href)[^\s>]*)*。您想要的是捕获\s*href=["']([^"']+)["']。
发布于 2016-05-17 01:12:57
您可以使用非常简单的正则表达式来解析这些值,使用非贪婪的“点”(.*?)的概念。虽然点将匹配任何内容,但它一次只使用一个字符,然后让模式的其余部分(双引号分隔符)匹配。您可以添加一些命名组,以提高可读性和访问结果:
href="(?<href>.*?)"|src="(?<imgsrc>.*?)" //globalhttps://stackoverflow.com/questions/37258873
复制相似问题