我在textarea中有这样的html:
<dl>
<dt>lorem</dt>
<dd>
<h1>heading</h1>
<p>ipsum</p>
</dd>
</dl>
现在,我想将它们存储在一个数组中:
$arr = explode("\n", $input);
结果如下:
Array ( [0] =>
<dl>
[1] =>
<dt>lorem</dt>
[2] =>
<dd>
[3] =>
<h1>heading</h1>
[4] =>
<p>ipsum</p>
[5] =>
</dd>
[6] =>
</dl>
)
现在,我如何迭代它们以获取dt和dd中的html或文本?
$dt = '';
$dd = '';
foreach($arr as $key => $value){
???
}
echo $dt;
echo $dd;
答案 0 :(得分:0)
答案 1 :(得分:0)
虽然我不建议你使用 foreach 来迭代你的数组(你应该使用而不是),这是你问题的解决方案:
foreach ($arr as $key => $value)
if (strpos($value, 'dt') !== false) {
$dt = $value;
} else if (strpos($value, 'dd') !== false) {
$dd = $value;
}
}
答案 2 :(得分:0)
我建议您使用本机PHP DOM扩展,以避免与html解析斗争。
http://php.net/manual/fr/book.dom.php
这是一个关于如何做你正在寻找的事情的简单例子:
<?php
$dom = new DOMDocument('1.0', 'iso-8859-1');
$dom->loadHTML($your_html_string);
$dom = $dom->getElementById($id_of_your_textarea);
foreach ($dls as $dl) {
echo $dl->nodeValue;
}
它应该是这样的。 (未经测试)
答案 3 :(得分:0)
使用DOMDocument
的力量:
$html_str = '<dl>
<dt>lorem</dt>
<dd>
<h1>heading</h1>
<p>ipsum</p>
</dd>
<dt>lorem2</dt>
<dd>
<h1>heading2</h1>
<p>ipsum2</p>
</dd>
</dl>';
function grabTextareaDl($html_str, $type = 'text') {
$doc = new DOMDocument();
$doc->loadHTML($html_str);
$dl = $doc->getElementsByTagName("dl")->item(0);
$dt = $dd = [];
$getInnerHtml = function(DOMNode $node){
$html = "";
foreach ($node->childNodes as $n) {
$html .= $node->ownerDocument->saveHTML($n);
}
return $html;
};
foreach ($dl->childNodes as $n) {
if ($n->nodeName == 'dt' || $n->nodeName == 'dd') {
if ($type == 'html') {
${$n->nodeName}[] = $getInnerHtml($n);
} else {
${$n->nodeName}[] = $n->nodeValue;
}
}
}
return ['dt' => $dt, 'dd' => $dd];
}
print_r(grabTextareaDl($html_str));
输出(文字):
Array
(
[dt] => Array
(
[0] => lorem
[1] => lorem2
)
[dd] => Array
(
[0] =>
heading
ipsum
[1] =>
heading2
ipsum2
)
)
print_r(grabTextareaDl($html_str, "html"));
输出(html):
Array
(
[dt] => Array
(
[0] => lorem
[1] => lorem2
)
[dd] => Array
(
[0] =>
<h1>heading</h1>
<p>ipsum</p>
[1] =>
<h1>heading2</h1>
<p>ipsum2</p>
)
)