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

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

问题描述

可能的重复:
解析 HTML 的最佳方法

如何解析保存在 PHP 变量中的 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.

推荐答案

使用 PHP 文档对象模型:

<?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/>";
?>

这输出为:

 T1
 T2
 T3

<小时>

:OP 澄清后:

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

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);
?>

这个输出:

Lorem ipsum.敏捷的红狐狸……跳过懒惰的棕色青蛙

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

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

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