【发布时间】:2011-02-08 12:58:36
【问题描述】:
我正在尝试使用两个 preg_match 以便从 html 源代码中获取两个特定值。
<?php
$url = "http://www.example.com";
$userAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1";
$ch = curl_init();
curl_setopt($ch,CURLOPT_USERAGENT,$userAgent);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_AUTOREFERER,true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_TIMEOUT,10000000);
$html = curl_exec($ch);
preg_match('~<span class="first">(.*)<\/span>~msU',$html,$matching_data);
preg_match('~<span class="second">(.*)<\/span>~msU',$html,$matching_data2);
print_r($matching_data);
print_r($matching_data2);
?>
考虑到$html var 包含以下序列:
<title>foobar title</title>
<body>
<div class="second">Not this one</span>
<div>
<span class="first">First</span>
<span class="second">this one<span>
</div>
</body>
如果我运行 php 代码,第一个 print_r 返回正确的值:<span class="first">First</span>。但是第二个print_r,不是返回<span class="second">this one<span>,而是返回<div class="second">Not this one</span>。
所以我猜preg_match 函数从头开始处理,而不是最后一个preg_match 调用。
如何让preg_match 的第二次(第三次、第四次等)呼叫在最后一次呼叫时运行?
谢谢,
问候。
【问题讨论】:
-
你可以使用 preg_match_all。
-
如何在我的情况下使用 preg_match_all?谢谢。
标签: php regex preg-match