我在正则表达式代码中找不到错误

时间:2018-08-10 22:16:33

标签: php regex design-patterns

使用preg_match_all我想获取html中的类和数据属性。

我之前也问过类似的问题。 DOM是对先前职责的正确答案。但是作为DOM结构的替代方法,我还需要一个正则表达式版本。

该模式工作正常。但是,如果这些行是并排的,它们还将从不应该接受的标记中获取类名。

<div class="noproblem"> 
    <ul class="noproblem" data-ss="1">
        <li class="noproblem" data-ss="1">
            <!-- <i> is not my tag. but there s no problem with that. because it s underneath . -->
            <i class="no_problem"></i>
        </li>
    </ul>
</div>

<div class="noproblem" data-ss"1">  <!-- problem: data-ss is not accepted -->
    <ul class="noproblem" data-ss="1">
        <!-- <i> is not my tag. my tags:  div|ul|li . -->
        <li class="noproblem"><i class="this_is_problem"></i>
        </li>
    </ul>
</div>

<div class="noproblem">
    <ul class="noproblem">
        <!-- <i> is not my tag. my tags:  div|ul|li . -->
        <li class="noproblem"><i class="this_is_problem"></i>
        </li>
        <!-- <span> is not my tag. my tags:  div|ul|li . -->
        <li class="test"><span class="this_is_problem"></span></li>
        <!-- (li class empty version): <span> is not my tag. my tags:  div|ul|li . -->
        <li><span class="this_is_problem"></span></li>
    </ul>
</div>

正则表达式模式:

$pattern = '/<(?:div|ul|li)(?:.*?(?:class|data-ss)="([^"]+)")?(?:.*?(?:class|data-ss)="([^"]+)")?[^>]*>/'; 

示例和问题:https://regex101.com/r/vSIsac/5

替代来源(我的老问题):https://stackoverflow.com/a/51778865/6320082

1 个答案:

答案 0 :(得分:1)

如果您确实需要使用正则表达式,请尝试以下操作:

<(?:div|ul|li)(?=[^>]*\bclass="([^"]+)")(?=(?:[^>]*\bdata-\w+="([^"]+)")?)

您将在第一个捕获组($1)上获得类别值,在第二个捕获组($2)上获得数据值(如果存在)

Demo

说明:

<(?:div|ul|li)  # div or ul or li tag

 # Lookahead expressions:

 # find any character not '>' repeated any times, then class
 (?= # lookahead
    [^>]*\bclass="([^"]+)"
 )  

 # find any character not '>' repeated any times, then data
 # Since this is optional, we make the whole expression optional with ?
 (?=
    (?:
        [^>]*\bdata-\w+="([^"]+)"
    )? # optional
 )