php匹配div的正则
时间: 2023-10-02 11:07:08 浏览: 39
以下是一个匹配HTML中`<div>`标签的正则表达式,使用PHP的话,可以使用preg_match_all函数:
```php
$pattern = '/<div\s[^>]*>/i';
$str = '<div class="my-class" id="my-id">This is a div</div>';
preg_match_all($pattern, $str, $matches);
print_r($matches);
```
解释一下正则表达式:
- `<div>`:匹配`<div>`标签;
- `\s`:匹配一个空白字符;
- `[^>]*`:匹配除了`>`以外的任意字符,重复0或多次;
- `i`:不区分大小写。
这个正则表达式可以匹配如下形式的`<div>`标签:
```html
<div>
<div class="my-class">
<div id="my-id">
<div class="my-class" id="my-id">
```
相关问题
php 正则匹配DIV
以下是匹配DIV的 PHP 正则表达式:
```
/<div\b[^>]*>(.*?)<\/div>/si
```
解释:
- `<div`:匹配 DIV 标签的开头;
- `\b`:单词边界,确保不会匹配到 DIV 的子串;
- `[^>]*`:匹配除了 ">" 以外的任意字符,确保 DIV 标签内的属性和值不会影响匹配结果;
- `(.*?)`:懒惰匹配,匹配 DIV 内的任意内容;
- `<\/div>`:匹配 DIV 标签的结尾;
- `/si`:正则表达式修饰符,使正则表达式忽略大小写(i)并且 "." 能够匹配换行符(s)。
使用示例:
```php
$pattern = '/<div\b[^>]*>(.*?)<\/div>/si';
$string = '<div class="content"><p>This is a DIV.</p></div>';
preg_match($pattern, $string, $matches);
print_r($matches);
```
输出结果:
```
Array
(
[0] => <div class="content"><p>This is a DIV.</p></div>
[1] => <p>This is a DIV.</p>
)
```
其中,$matches[0] 表示匹配到的整个 DIV 标签,$matches[1] 表示 DIV 内的内容。
php 根据class 正则匹配DIV
以下是一个例子,可以匹配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`修饰符表示"."也可以匹配换行符。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)