Sohaib
Sohaib

Reputation: 1

replace div with its content

i am trying to filter an html code

the code contains a div's with row class

i want to replace these div's with there contents

for ex:

<div class="row anotherClass">some html code 1</div>
<div class="row anotherClass">some html code 2</div>
<div class="row anotherClass">some html code 3</div>

output should be like this

some html code 1
some html code 2
some html code 3

i have wrote the following expression (i am not very good with regex) but the output html is still not well filtered some times the div beginning still exist some times the div end still exist

$output = preg_replace_callback('/<div class="row (.*?)">(.*)<\/div>/s', function ($matches) {
            return $matches[2];

        }, $output);

Upvotes: 0

Views: 1321

Answers (1)

Meowing Cat
Meowing Cat

Reputation: 152

Do you mean this?

<?php

$html = '<div class="row anotherClass">some html code 1</div>
<div class="row anotherClass">some html code 2</div>
<div class="row anotherClass">some html code 3</div>';

$reg = '(<div class="row anotherClass">(.*?)</div>)';
preg_match_all($reg, $html, $divs);

$div_contents = $divs[1];
$divs = $divs[0];

$replaced_html = $html;

for ($i=0; $i < count($divs); $i++) {
    $replaced_html = str_replace($divs[$i], $div_contents[$i], $replaced_html);
}

echo $replaced_html;

?>

Upvotes: 1

Related Questions