使用preg_match用PHP

时间:2015-11-04 10:52:13

标签: php preg-match

我正在使用preg_match()来提取 -
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)

从此 -
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>



我的代码没有工作,只返回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 个答案:

答案 0 :(得分:0)

例如,你想匹配&#34;罗伯特去了。&#34;在&#34;罗伯特·温特。我从未意识到什么时候。
&#34;你应该按照以下方式使用preg_match()

$text = "<span style='color: #999;'>Robert Went.I never realized when.<br />";

$matches = array();

preg_match("/.*(Robert Went\.).*/", $text, $matches);

答案 1 :(得分:0)

我会说enter image description here是你的朋友,但如果你真的想用preg_match来解决这个问题,你可以试试这个:

$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 );

<强>更新

如果你不能上课,试试这个:

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

输出将是:

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 :(得分:0)

您似乎只是从字符串中删除所有html代码(span标记)(以及第一部分'3天天气预报摘要:')。为什么不检测所有<>?类似的东西:

$text = preg_replace('/<.*?>/', '', $text);
$text = trim(substr($text, strlen('3 Day Weather Forecast Summary:')));

第一行用空字符串替换<>(包括)中的所有文本。 ?是为了让它不贪婪,只有匹配 <>才会被删除。

第二行只删除前导字符串。由于它可能有也可能没有前导空格,我还包括trim函数,但这可能没有必要。

显然,这两行也可以组合成一行。