html的正则表达式

时间:2010-08-30 20:46:32

标签: php html regex

  

可能重复:
  RegEx match open tags except XHTML self-contained tags

我有以下字符串:

$str = " 
<li>r</li>  
<li>a</li>  
<li>n</li>  
<li>d</li>  
...
<li>om</li>  
";

如何获取第n个<li>代码的HTML?

Ex : n = 3 ; result = "<li>r<...>n</li>;

如果可能,我想要一个正则表达式。

3 个答案:

答案 0 :(得分:10)

喜欢这个。

$dom = new DOMDocument();
@$dom->loadHTML($str);
$x = new DOMXPath($dom); 

// we wan the 4th node.
foreach($x->query("//li[4]") as $node) 
{
  echo $node->c14n()
}

哦,是的,学习xpath,这将为你节省很多麻烦。

答案 1 :(得分:6)

@Byron的解决方案,但使用SimpleXML:

$xml = simplexml_load_string($str);

foreach($xml->xpath("//li[4]") as $node){
  echo $node[0]; // The first element is the text node
}

编辑:我非常喜欢simplexml的另一个原因是可以轻松调试节点内容。你可以使用print_r($ xml)用它的子节点打印对象。

答案 2 :(得分:1)

我确信你知道使用正则表达式来处理HTML不是一个好主意,除非你先“整理”它。

PHP中一个非常可行的解决方案是使用Simple XML(http://php.net/manual/en/book.simplexml.php)或DOM文档(http://php.net/manual/en/class.domdocument.php)来导航HTML结构。