如何使用PHP将所有类从html获取到数组

时间:2019-06-27 02:42:19

标签: php regex

有些事情似乎很简单,但是从昨天开始,这件事就一直杀了我。

到目前为止,我有一个CSS文件style.css,我已经能够解析数组中的所有内容。那里一切都很好。

我似乎无法弄清楚的是如何从html文件中获取所有类,以便可以将其与CSS数组进行比较。

我的代码示例如下

      <div id="idtest" class="flex-center position-ref full-height">
            <div class="flex-test1">
                 <div class="flex-test2">
                 </div>
            </div>
      </div>

我一直在尝试使用preg_match,但我只能得到class =“ test”,而且似乎也不能拉出文件中所有的内容,而只会拉出第一个。

        preg_match('/class=".*?"/i', $value, $match);
        print_r($match);
(
 [id] => Array
        (
            [0] => idtest

        )
    [class] => Array
        (
            [0] => flex-center
            [1] => position-ref
            [2] => full-height
            [3] => flex-test1
            [4] => flex-test2

        )
)

2 个答案:

答案 0 :(得分:0)

我认为您可以尝试使用jQuery.each()[在这里] https://api.jquery.com/each/ 它将对DOM元素进行迭代,然后您就可以获取该类。.(我没有50信誉可将其作为注释,所以..)

答案 1 :(得分:0)

您设计的表达式很好,我们可能想添加一个捕获组,并且该问题可能已解决:

$re = '/class="\s*(.*?)\s*"/s';
$str = '      <div id="idtest" class="flex-center position-ref full-height">
            <div class="flex-test1">
                 <div class="flex-test2">
                 </div>
            </div>
      </div>';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches);

如果您感兴趣,请在此demo中对表达式进行说明。