Bajlo
Bajlo

Reputation: 1417

String replace function only for the content inside of a specified html tag

I need to use string replace function but only for the content inside of a specified html tag.

For expample I want to replace all strings type=checkbox to type=radio only inside of div id=category tag. Function str_replace('type="checkbox" ', 'type="radio" ', $content) does it for every string.

<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>

Any ideas how to do it? Thanks

Upvotes: 0

Views: 715

Answers (1)

m59
m59

Reputation: 43745

First, please note that id's must be unique within a document. You are using the same id's on each set of inputs, and that is invalid.

I recommend parsing and replacing the html with DOMDocument: 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;

Upvotes: 1

Related Questions