Kartik
Kartik

Reputation: 9853

Help with looping for an array with key and value

I am trying to make this function that extracts text from html for multiple steps but I cant figure out how to make a loop form it.

This is the task. I have this array

$arr = array("<div>" => "</div>", "<p>" => "</p>", "<h3>" => "</h3>");

The existing working function cut($a, $b, $c) that gets the content in between in this case $a = "<div>", $b="</div>" and $c = the html.

What i am trying to do is to make this:

Although I know that I can use foreach to get the results and apply step two, I cant generalize this.

EDIT

I have an existing function called cut that has been described above. I want to create a new function called cutlayer($arr, $html) where $arr is arr from above. I need the cutlayer function to use the cut function and do the following steps mentioned above but I cant figure out how to do that.

Thanks

Upvotes: 0

Views: 102

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270637

Save yourself the trouble and use a toolkit designed for parsing HTML. PHP's DOMDocument is made for these tasks.

$dom = new DOMDocument();
$dom->loadHTML($yourHTML);
$divs = $dom->getElementsByTagName("div");

// Get the inner contents of all divs, for example
foreach ($divs as $div) {
  echo $div->nodeValue;
}

Unless this is homework and you were instructed to use your array matching method....

Upvotes: 3

Related Questions