我使用正則表達式來匹配頁面中的特定div,並用自定義格式替換它們。我無法使用domdocument,因爲我們處理的頁面經常是畸形的,在通過domdocument運行後,頁面會被重新格式化並且不會顯示相同的內容。php - 正則表達式來匹配div標籤
我目前使用它完美的作品如下:
preg_match('#(\<div id=[\'|"]'.$key.'[\'|"](.*?)\>)(.*?)\<\/div\>#s', $contents, $response);
要匹配div標籤,如:
<div id="test"></div>
<div id="test" style="width: 300px; height: 200px;"></div>
etc...
這個問題我現在遇到的標籤,其中ID是在後樣式或類,例如:
<div class="test" id="test"></div>
如果我運行以下,正則表達式似乎變成貪婪y並在div標籤之前匹配了大量html,所以我不知道如何解決此問題:
preg_match('#(\<div(.*?)id=[\'|"]'.$key.'[\'|"](.*?)\>)(.*?)\<\/div\>#s', $contents, $response);
有沒有人有任何想法?
看看這個,可能對你有點幫助:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags –
[必備鏈接] (http://stackoverflow.com/q/4231382/471272)。 – tchrist