我需要使用字符串替换功能,但仅限于指定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>
任何想法怎么做?感谢
答案 0 :(得分:1)
首先,请注意,id在文档中必须是唯一的。您在每组输入上使用相同的ID,这是无效的。
我建议使用DOMDocument
解析和替换html: Live demo (click).
$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;