php explode选择多选

时间:2011-07-01 12:48:59

标签: php explode

我想将这些html划分为serval的几个部分。一个<h2><h3>,其中一些<p><span>为一部分。我尝试了explode array('<h2>','<h3>'),但却导致了Warningexplode不支持多选。

那么如何做到完美呢?感谢。

$text=<<<EOT
<h2>title1</h2>
<p>something</p>
<span>something</span>
<h3>title2</h3>
<p>something</p>
<p>something</p>
<p>something</p>
<h2>title3</h2>
<span>something</span>
<h2>title4</h2>
<span>something</span>
<p>something</p>
<p>something</p>
EOT;

foreach ($text as $result) { 
    $arr = explode(array('<h2>','<h3>'),$result);
    reset($arr); 
    foreach($arr as $line){
        echo $line.'<hr />';
    } 
}

Warning: Invalid argument supplied for foreach() on line 23;

我的预期输出是:

<h2>title1</h2>
<p>something</p>
<span>something</span>
___________________________
<h3>title2</h3>
<p>something</p>
<p>something</p>
<p>something</p>
___________________________
<h2>title3</h2>
<span>something</span>
___________________________
<h2>title4</h2>
<span>something</span>
<p>something</p>
<p>something</p>
___________________________

3 个答案:

答案 0 :(得分:1)

您应该使用解析器来执行此类任务。我使用Zend Framework,它有一个parser component。否则,您可以使用普通PHP DOMElement。然后,您可以使用xpath或css选择器查​​询您的dom。例如:

<?php

$text=<<<EOT
<h2>title1</h2>
<p>something</p>
<span>something</span>
<h3>title2</h3>
<p>something</p>
<p>something</p>
<p>something</p>
<h2>title3</h2>
<span>something</span>
<h2>title4</h2>
<span>something</span>
<p>something</p>
<p>something</p>
EOT;


require_once 'Zend/Dom/Query.php';

$dom = new Zend_Dom_Query($text);
$results = $dom->query('h2');

foreach ($results as $domEl) {
    var_dump($domEl->nodeValue);
}
// outputs:
// string(6) "title1"
// string(6) "title3"
// string(6) "title4"

编辑:鉴于您的预期输出,我的示例并不完全符合您的需求,但您仍然需要一个解析器来执行这种HTML操作,因为解析器会在元素中拆分HTML你可以把它们当作代币来操纵,而不是文本。

答案 1 :(得分:1)

您可以在不同的事情上使用preg_split()explode。您可以在此处使用RegEx:

$text = <<<EOT
<h2>title1</h2>
<p>something</p>
...
EOT;

$arr = preg_split("#(?=<h[23]>)#", $text);

if(isset($arr[0]) && trim($arr[0])=='') array_shift($arr); // remove first block if empty

foreach($arr as $block){
    echo $block."<hr />\n";
}

答案 2 :(得分:1)

好的,首先,警告发送到foreach,而不是explode。您正在尝试循环string(在这种情况下为$text)而不是array

其次,即使$text属于数组类型且$result属于字符串类型,您也试图在explode()调用中使用array作为分隔符,但该函数希望第一个参数的类型为string

我建议您查看How to parse HTML with PHP?search SO这些术语,以查找许多有关如何使用PHP解析HTML的帖子。