php 根据class 正则匹配DIV
时间: 2023-09-12 15:13:23 浏览: 76
(很有用)PHP中正则表达式详细说明
以下是一个例子,可以匹配HTML中所有class为"my-class"的div标签:
```php
$html = '<div class="my-class">This is a div with class "my-class".</div><div class="other-class">This is a div with class "other-class".</div>';
preg_match_all('/<div class="my-class".*?>.*?<\/div>/s', $html, $matches);
print_r($matches);
```
输出结果为:
```
Array
(
[0] => Array
(
[0] => <div class="my-class">This is a div with class "my-class".</div>
)
)
```
解释一下正则表达式:
`/<div class="my-class".*?>.*?<\/div>/s`
- `<div class="my-class"`:匹配div标签的开头,且class属性为"my-class"
- `.*?`:匹配任意字符,且尽可能少
- `<\/div>`:匹配div标签的结尾
最后的`s`修饰符表示"."也可以匹配换行符。
阅读全文