preg_match_all 用 class 得到 div

preg_match_all get div with class

我想获取 div 内容,但我的问题是引号。示例 divs:

<div class="fares" style=''> here html div content </div>
<div class="fares2" style=""> here html div content </div>
<div class='fares2' style="border:1px solid #cc"> here html div content </div>

引号有时是单引号 (') 有时是双引号 (") 并且样式相同。如何获得所有 faresfares2 divs?

Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.

可以使用 xpath starts-with 函数: //div[starts-with(@class,"fares")]

完整示例:

<?php

$html = <<<EOD
<div class="fares" style=''> here html div content1</div>
<div class="fares2" style=""> here html div content2</div>
<div class='fares2' style="border:1px solid #cc"> here html div content3</div>
EOD;

$dom = new DOMDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;

$xpath = new DOMXPath($dom);
$divs = $xpath->query('//div[starts-with(@class,"fares")]');
if ($divs->length > 0) {
    foreach ($divs as $key => $div) {
        print_r($div);
    }
}