duancha1065 2015-11-04 10:52
浏览 77
已采纳

使用preg_match用PHP提取内容

I am using preg_match() to extract this -

Mostly dry. Very mild (max 16°C on Fri afternoon, min 12°C on Tue night). Winds decreasing (fresh winds from the N on Wed morning, calm by Wed night)

From this -

3 Day Weather Forecast Summary:</b><span class="read-more-small"><span class="read-more-content"> <span class="phrase">Mostly dry. Very mild (max 16&deg;C on Fri afternoon, min 12&deg;C on Tue night). Winds decreasing (fresh winds from the N on Wed morning, calm by Wed night).</span>



My code isn't working and just returns Array ( )

$contents = "3 Day Weather Forecast Summary:<\/b><span class=\"read-more-small\"><span class=\"read-more-content\"> <span class=\"phrase\">Mostly dry. Very mild (max 16&deg;C on Fri afternoon, min 12&deg;C on Tue night).
Winds decreasing (fresh winds from the N on Wed morning, calm by Wed night).</span>";

preg_match('/3 Day Weather Forecast Summary:<\/b><span class="read-more-small"><span class="read-more-content"> <span class=\"phrase\"> (.*?) </s', $contents, $matches);

print_r($matches);
  • 写回答

3条回答 默认 最新

  • dongxue163536 2015-11-04 11:07
    关注

    I would say DOMDocument is your friend, but if you are really want to solve this with preg_match you cpuld try this one:

    $contents = "3 Day Weather Forecast Summary:<\/b><span class=\"read-more-small\"><span class=\"read-more-content\"> <span class=\"phrase\">Mostly dry. Very mild (max 16&deg;C on Fri afternoon, min 12&deg;C on Tue night).
    Winds decreasing (fresh winds from the N on Wed morning, calm by Wed night).</span>";
    
    preg_match( '@<span class="phrase">(.*?)</span>@s', $contents, $matches);
    
    var_export( $matches );
    

    UPDATE:

    if you can't go for classes, try this:

    preg_match( '@3 Day Weather Forecast Summary:.*?<span class="read-more-content"> <span class="phrase">(.*?)</span>@s', $contents, $matches);
    

    The output will be:

    Array
    (
        [0] => <span class="phrase">Mostly dry. Very mild (max 16&deg;C on Fri afternoon, min 12&deg;C on Tue night).
    Winds decreasing (fresh winds from the N on Wed morning, calm by Wed night).</span>
        [1] => Mostly dry. Very mild (max 16&deg;C on Fri afternoon, min 12&deg;C on Tue night).
    Winds decreasing (fresh winds from the N on Wed morning, calm by Wed night).
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题