2

我的php代码中的函数:

private function get_first_images($html){
    preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $html, $matches);
    if(isset($matches[1]) && isset($matches[1][0]) && !empty($matches[1][0])){
        return $matches[1][0];
    }else{
        return false;
    }
}

正在拉第二张图片而不是第一张。这是它正在查看的 xml 示例:

<![CDATA[
<a href="http://mls-photos.diversesolutions.com/355/1246202/0-full.jpg?15054836" target="_blank"><img src="http://mls-photos.diversesolutions.com/355/1246202/0-medium.jpg?15054836" alt="Property Photo" /></a><br /><br /><img src="http://cdn1.diverse-cdn.com/idx-v2/mls-icons/rein.png" alt="Mls Icon" /><br /><br /><b>3 beds, 2 full, 1 part baths</b><br />Home size: 1,700 sq ft<br />Lot Size: 0 sq ft<br />Property Type: Residential, Residential / Detached<br />MLS Number: 1246202<br />Community: North Norfolk<br />Tract: East Beach<br /><br /><br />Beautiful New Home With Wrap Around Porch, 10 Ft. Ceilings On First Floor, Hardwood Floors, Custom Cabinets, Granite, One Block To The Beach. Real Cedar Shake Exterior. Corner Lot. Carriage House Unfinished. <br /><br />Listed with Keller Williams Realty<br /><hr noshade="noshade" /><br /><b>Brought to you by Virginia Beach Real Estate Team, Keller Williams Realty. Call me today at 757-215-4246, or visit my website at <a href="http://www.vbret.com" target="_blank">www.vbret.com</a>!</b><br /><br /><p>Users of this Site are granted a limited, nonexclusive license to use the Site and its listing content for personal and noncommercial use only.
 </p>
 <p>
 Real Estate Information Network, Inc. (REIN) updates its listings on a daily basis. Data last updated: 12/21/12 7:55 AM PST. Some properties which appear for sale on this website may have subsequently sold or may no longer be available.
 </p>
 <p>
 All Information Deemed Reliable But Not Guaranteed.
 </p>
 <p>
 REIN's listings are based upon data submitted by its Broker Members, and REIN therefore makes no representation or warranty regarding the accuracy of the data. All users of REIN's listings database should confirm the accuracy of the listing information directly with the listing agent. This data and information is protected under Federal Copyright laws. Federal law prohibits, among other acts, the unauthorized copying or alteration of, or preparation of derivative works from, all or any part of copyrighted materials, including certain compilations of data and information. COPYRIGHT VIOLATORS MAYBE SUBJECT TO SEVERE FINES AND PENALTIES UNDER FEDERAL LAW.
 </p><hr noshade="noshade" />
]]>

如何修复它以使其拉出第一个图像而不是第二个图像?

4

1 回答 1

2

您需要使 + ungreedy :

private function get_first_images($html){
    preg_match_all('/<img.+?src=[\'"]([^\'"]+)[\'"].*>/i', $html, $matches);
    if(isset($matches[1]) && isset($matches[1][0]) && !empty($matches[1][0])){
        return $matches[1][0];
    }else{
        return false;
    }
}
于 2012-12-21T17:11:50.700 回答