我将如何在2个场景中使用preg_replace regex?

时间:2012-07-11 20:02:51

标签: php regex

我试图在某些页面上获取图像的来源,但两页的代码之间存在一些差异。

Page 1代码:

<img class="thumb thumb_0" onclick="setImage(0); return false;" src="http://example.com/b1.jpg">

Page 2代码:

<img style="width: 46px ! important; height: 46px ! important;" class="thumb thumb_0" onclick="setImage(0); return false;" src="http://example.com/image4.jpg">

注意两个页面之间的区别... Page 2在img标签的开头有一个愚蠢的样式。此外,“onclick”位于不同的位置。我唯一需要抓住的是图像位置。

这是我到目前为止的代码......仅适用于第1页场景:

preg_match_all("/<img\s*?class='thumb.*?'.*?src='(.*?)'.*?\/>/is", $hotelPage, $thumbs, PREG_PATTERN_ORDER);

理想情况下,我希望能够将它保存在一个php行中。如何在preg_replace中执行“或”,如何让正则表达式也适用于第2页?

提前谢谢!

更新:页面有其他图像,我只查找那些包含“拇指”的类。我为遗漏那些沉重的细节道歉。

4 个答案:

答案 0 :(得分:2)

网络上有关于HTML属性的多个正则表达式示例。一个应该适用于您的两个特定情况,以及几乎任何其他image-src将是:

preg_match_all("/<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>/", $hotelPage, $thumbs);

有关此特定正则表达式的详细信息,请访问:Regular expression to get an attribute from HTML tag

一个更加修改的版本,处理'class =“thumb *”'规则将是:

preg_match_all("/<img[^>]+class=\"thumb[^\"]*\"[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>/", $hotelPage, $thumbs);

答案 1 :(得分:1)

这应该按照您的意图运行 - 如果您的html位于$html,则正则表达式看起来应该像$reg

$html='some html <img class="thumb thumb_0" onclick="setImage(0); return false;"
   src="http://example.com/b1.jpg"> xxx yyy <img class="bummer thumb_0"
   onclick="setImage(0); return false;" src="http://example.com/bummer.jpg">
   <img style="width: 46px ! important; height: 46px ! important;"
   class="thumb thumb_0" onclick="setImage(0); return false;"
   src="http://example.com/image4.jpg"> some html';

$reg = ' <img .+?                # img tag
         class="thumb .+?        # class tag
         src="([^"]+)            # capture src
       ';

preg_match_all("/$reg/xis", $html, $thumbs, PREG_SET_ORDER);

foreach($thumbs as $t) echo $t[1]."\n";

如果属性顺序为{class, src} ,并且同时找到了img-tag和正确的类“thumb”,则匹配 。我们走了:

http://example.com/b1.jpg
http://example.com/image4.jpg

三个img条目中只有两个匹配(我在测试集中包含了第三个错误的链接)。

此致

RBO

答案 2 :(得分:0)

如果您想要的只是src,那么您应该忽略正则表达式中的所有其他内容。

尝试:

/<img\s.*src='(.*)'.*>/iu

作为你的正则表达式。

答案 3 :(得分:0)

不建议使用正则表达式来解析xml / html。你应该看到这个问题:RegEx match open tags except XHTML self-contained tags

你能做的就是使用像DOMDocument这样的东西来找出网址:

$html = '<img class="thumb thumb_0" onclick="setImage(0); return false;" src="http://example.com/b1.jpg">
<img style="width: 46px ! important; height: 46px ! important;" class="thumb thumb_0" onclick="setImage(0); return false;" src="http://example.com/image4.jpg">';

$dom = new DOMDocument();
$dom->loadHTML($html);
$images = $dom->getElementsByTagName('img');

$image_urls = array();
foreach ($images as $image) {

    // only match images with class thumb
    if (strpos(' ' . $image->getAttribute('class') . ' ', ' thumb ') !== false) {
        $image_urls[] = $image->getAttribute('src');
    }
}

var_dump($image_urls);