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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。