PHP解析HTML代码 [英] PHP Parse HTML code

查看:85
本文介绍了PHP解析HTML代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

解析HTML的最佳方法


如何解析HTML代码保存在PHP变量中,如果它是这样的:

 < h1> T1< / h1> Lorem ipsum。< h1> ; T2< / h1>快速红狐......< h1> T3< / h1>跳过懒惰的棕色FROG! 

我想要只显示标题之间的文字使用正则表达式不是一个好主意。

使用PHP .net / manual / en / book.dom.phprel =noreferrer>文档对象模型

 <?php 
$ str ='< h1> T1< / h1> Lorem ipsum。< h1> T2< / h1>快速红色狐狸< h1> T3< / h1> ...跳过懒惰的棕色FROG';
$ DOM = new DOMDocument;
$ DOM-> loadHTML($ str);

//获取所有H1
$ items = $ DOM-> getElementsByTagName('h1');

//显示所有的H1文本
($ i = 0; $ i< $ items->长度; $ i ++)
echo $ items-> item ($ i) - > nodeValue。 <峰; br /> 中;
?>

输出为:

  T1 
T2
T3






:在OP说明之后



如果您想要像 Lorem ipsum这样的内容。 等等,你可以直接使用这个正则表达式:

 <?php 
$ str ='< h1> T1< / h1> Lorem ipsum。< h1> T2< h1>快速红狐狸......< h1> T3< / h1>跳过懒惰的褐色FROG';
echo preg_replace(#< h1。*?>。*?< / h1>#,,$ str);
?>

此输出:


Lorem ipsum。快速的红色狐狸......跳过懒惰的棕色FROG



Possible Duplicate:
Best methods to parse HTML

How can I parse HTML code held in a PHP variable if it something like:

<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG!

I want to only get the text that's between the headings and I understand that it's not a good idea to use Regular Expressions.

解决方案

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3


[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

这篇关于PHP解析HTML代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆