Search code examples
phppreg-match

Using preg_match to extract contents with 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);

Solution

  • 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).
    )