如何在PHP中使用regex从标记中获取pc或dc


How to get the pc or dc from a tag using regex in PHP?

在一个页面中有很多次这个标签

<div class="clsfd_thumb_container pc">

和这个标签

<div class="clsfd_thumb_container dc">

唯一的区别是pcdc

我想做的是将所有匹配的pcdc保存在一个数组中,并对它们进行回显。

我只需要正则表达式来匹配所有的pcdc

我该怎么做?非常感谢。

尝试以下操作:

[pd]c(?=">)
  • [pd]:匹配pd
  • c:当然和c很匹配
  • (?=">):如果后面跟着",然后是>,那么它只匹配我上面列出的内容

在PHP中,可以使用preg_match_all()提取所有匹配项,将上面的正则表达式作为第一个参数中的字符串传递。

preg_match_all('/[pd]c(?=">)/', $str, $dealers);
                ^           ^

Regex101演示

您实际上并不需要regex,只需使用strpos 即可

if(strpos($div_tag, 'dc') || strpos($div_tag, 'pc')) {
    $array[] = $div_tag;
}