使用正則表達式和PHP我試圖獲得標題屬性的內容如下。正則表達式匹配下一個屬性,如果找不到所需的屬性。如何限制它?
preg_match('/<abbr class="dtstart" title="([^"]*)"/i', $file_string, $starts);
$starts_out = $starts[1];
preg_match('/<abbr class="dtend" title="([^"]*)"/i', $file_string, $ends);
$ends_out = $ends[1];
這裏是我想要得到的代碼的確切部分,並且我正確地獲取了數據。
<div id="eventDetailInfo">
<h2>When</h2>
<div class="p">
<div>From:
<abbr class="dtstart" title="2012-08-24T17:00:00">Friday, August 24th, 2012</abbr></div>
<div>Until:
<abbr class="dtend" title="2012-08-26">Saturday, August 25th, 2012</abbr></div>
</div>
</div>
然而,因爲有時候沒有直到在一些文章,正則表達式匹配的第一個剩餘的代碼(這是相關文章)。
我的問題是如何限制的正則表達式來只匹配上面,如果沒有
<div>Until:
<abbr class="dtend" title="2012-08-26">Saturday, August 25th, 2012</abbr></div>
發現,留空白?
這是頁面的其餘代碼,不幸的是正則表達式匹配它。
<div class="evdate">
<em>When:</em>
<abbr class="dtstart" title="2012-07-03T21:00:00">July 3rd</abbr>
to
<abbr class="dtend" title="2012-07-13">July 12th</abbr>*
</div>
<div class="evtime"><em>Time:
</em>
21:00
</div>
</div>
使用[正則表達式來解析HTML是一個壞主意](http://stackoverflow.com/questions/1732348/regex-match- open-tags-except-xhtml-self-contained-tags) - 你應該嘗試使用XML解析器或類似的東西 – ernie 2012-07-31 17:01:03