字符串替换功能仅适用于指定的HTML标签内部的内容



我需要使用字符串替换函数,但仅适用于指定的HTML标签的内容。

对于老式,我想仅将所有字符串type=checkbox替换为type=radio div id=category标签的内部。功能str_replace('type="checkbox" ', 'type="radio" ', $content)适用于每个字符串。

<div id="category">
 ...
 <input id="in-1" type="checkbox"  value="1">
 <input id="in-2" type="checkbox"  value="2">
 <input id="in-3" type="checkbox"  value="3">
 ...
</div>
 ...
<div id="topic">
 ...
 <input id="in-1" type="checkbox"  value="1">
 <input id="in-2" type="checkbox"  value="2">
 <input id="in-3" type="checkbox"  value="3">
 ...
</div>

有什么想法如何做?谢谢

首先,请注意,ID在文档中必须是唯一的。您在每组输入上使用相同的ID,这是无效的。

我建议用DOMDocument实时演示(单击)。

$dom = new DOMDocument();
$dom->loadHtml('
<div id="category">
 <input type="checkbox" value="1">
 <input type="checkbox" value="2">
 <input type="checkbox" value="3">
 <!-- I added this element for testing that only checkboxes are changed -->
 <input type="text" value="3">
</div>
<div id="topic">
 <input type="checkbox"  value="1">
 <input type="checkbox"  value="2">
 <input type="checkbox"  value="3">
</div>
');
$cat = $dom->getElementById('category');
$inputs = $cat->getElementsByTagName('input');
foreach ($inputs as $k => $input) {
  if ($input->getAttribute('type') === 'checkbox') {
    $input->setAttribute('type', 'radio');  
  }
}
$newHtml = $dom->saveHtml();
echo $newHtml;

最新更新