加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 正则表达式匹配1个HTML文件中的2个html标签

发布时间:2020-12-13 22:01:40 所属栏目:PHP教程 来源:网络整理
导读:我有一个 HTML文件,其中包含以下内容: img src="MATCH1" bla="blabla"something:else bla="blabla" bla="bla"something:else2 something="something"something image="MATCH2" bla="abc" 现在我需要一个正则表达式匹配MATCH1和MATCH2 此外,HTML包含多个这样
我有一个 HTML文件,其中包含以下内容:

<img src="MATCH1" bla="blabla">
<something:else bla="blabla" bla="bla"><something:else2 something="something">
<something image="MATCH2" bla="abc">

现在我需要一个正则表达式匹配MATCH1和MATCH2

此外,HTML包含多个这样的部分,因此它可以在HTML的1,2,3中x次.

当我说:

<imgs*src="(.*?)".*?<somethings*image="(.*?)"

它与它不匹配.我在这里错过了什么?

提前致谢!

解决方法

Regex does not always provide perfect result while parsing HTML.

我认为你应该使用HTML DOM Parser

例如:

// Create DOM from URL or file
$html = file_get_html('http://www.example.com/');

// OR Create a DOM object from a HTML file
$html = file_get_html('test.htm');

// Find all images 
foreach($html->find('img') as $element) 
       echo $element->src . '<br>';

// Find all links 
foreach($html->find('a') as $element) 
       echo $element->href . '<br>';

有过滤器可以获取具有特定属性的标记:

[attribute] Matches elements that have
the specified attribute.

[attribute=value] Matches elements
that have the specified attribute with
a certain value.

[attribute!=value] Matches elements
that don’t have the specified
attribute with a certain value.

[attribute^=value] Matches elements
that have the specified attribute and
it starts with a certain value.

[attribute$=value] Matches elements
that have the specified attribute and
it ends with a certain value.

[attribute*=value] Matches elements
that have the specified attribute and
it contains a certain value.

More Options

还有一些其他解析工具来解析HTML,如this answer中所述.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读