tags:

views:

118

answers:

3

I have this string where I've put all opening tags into (array) $opened and all closing tags into (array) $closed, like so:

'<div>
    Test
 </div>

 <div>
    <blockquote>
       <p>The quick</p>
       <blockquote>
          <p>brown fox <span>jumps <span>over <img src="#" /> the'

Results in these two arrays:

$opened =

array(8) {
  [0]=> string(3)  "div"         // Need removed
  [1]=> string(3)  "div"
  [2]=> string(10) "blockquote"
  [3]=> string(1)  "p"           // Need removed
  [4]=> string(10) "blockquote"
  [5]=> string(1)  "p"
  [6]=> string(4)  "span"
  [7]=> string(4)  "span"
}

$closed =

array(2) {
  [0]=> string(3) "div"
  [1]=> string(1) "p"
}

I need to somehow say:

Find the first occurrence of $closed[0] (which is "div") in the $opened array and remove it from the $opened array, then repeat until all $closed tags ("div and "p") have been removed from the top of $opened.

A: 

I am not sure if this is what you are looking for, but this will remove the first instance of the thing you are looking for.

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$opened_tags = array("div", "div", "blockquote", "p", "blockquote", "p", "span", "span");
$closed_tags = array("div", "p");

$find = "div";

$size = sizeof($closed_tags);
for($i=0; $i<$size; $i++) {
    if($closed_tags[$i] == $find){
     unset($closed_tags[$i]);
     break;
    }
}

echo "closed_tags with empty spaces: ".print_r($closed_tags, true)."<br /><br />";

$closed_tags = array_values($closed_tags);
echo "closed_tags array indexed correctly: ".print_r($closed_tags, true)."<br />";
?>
lyscer
+1  A: 

Hope this helps someone. This is what I came up with:

<?php

    for ( $i = 0; $i < $num_closed; $i++ )
    {
        unset ( $opened[ array_search( $closed[ $i ], $opened ) ] );
    }

?>

I also came up with a for loop which worked, but you had to manipulate the $opened[$i] and $closed[$n] independently, and it was a bit more code, so I ultimately decided on this one.

Jeff
A: 

I cannot tell from your question, but if your aim is to clean up a snippet of html code, why not simply use the HTMLTidy extension?

Tutorial

Cups