1

I need to know how to iterate through this array and get the html content so that I can use it to make another array. The array I have is this:

$arr = array(
     "<span class='inside'>inside1</span> this is outside",
     "<span class='inside'>inside2</span> this is outside",
     "<span class='inside'>inside3</span> this is outside"
     );

and I want the following result:

$result = array(
   "inside1",
   "inside2",
   "inside3"
   );

I have tried the following but no results:

foreach ( $arr as $html){
   $dom = new DOMDocument();
   $dom->loadHTML($html);
   $xpath = new DOMXpath($dom);
   $result = $xpath->query('//span[@class="inside"]');
   echo $result
}

Please Help.

CodeGodie
  • 12,116
  • 6
  • 37
  • 66

4 Answers4

1

You could do this

$arr = array(
    "<span class='inside'>inside1</span> this is outside",
    "<span class='inside'>inside2</span> this is outside",
    "<span class='inside'>inside3</span> this is outside"
);

$insideHTML = array();
foreach($arr as $string) {
    $pattern = "/<span ?.*>(.*)<\/span>/";
    preg_match($pattern, $string, $matches);
    $insideHTML[] = $matches[1];
}
var_dump($insideHTML);

This will then give you the following array

array(3) {
  [0]=>
  string(7) "inside1"
  [1]=>
  string(7) "inside2"
  [2]=>
  string(7) "inside3"
}
Pattle
  • 5,983
  • 8
  • 33
  • 56
1
$arr = array(
     "<span class='inside'>inside1</span> this is outside",
     "<span class='inside'>inside2</span> this is outside",
     "<span class='inside'>inside3</span> this is outside"
     );

function clean($var)
{
$var=strip_tags($var);
$chunk=explode(' ',$var);
return $chunk[0];

}    

$inside = array_map("clean", $arr);
print_r($inside);
sinisake
  • 11,240
  • 2
  • 19
  • 27
0

For your exact example this would work:

$arr = array(
     "<span class='inside'>inside1</span> this is outside",
     "<span class='inside'>inside2</span> this is outside",
     "<span class='inside'>inside3</span> this is outside"
     );

$inside = array();

foreach($arr as $k=>$v){

    $expl1 = explode("<span class='inside'>", $v);

    foreach($expl1 as $k2=>$v2){

        $v2 = trim($v2);

        if(strpos($v2, '</span>') !== false){

            $expl2 = explode('</span>', $v2);

            $inside[] = $expl2[0];
        }

    }

}

print_r($inside);

Which produces:

Array
(
    [0] => inside1
    [1] => inside2
    [2] => inside3
)
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
0

If this is the only thing you need to do (as in, they are always going to be structured as <span>Inside</span>Oustide) You could do this:

$result=array();
foreach($arr as $html) {
    $result[]=substr(strstr(strstr($html,'>'),'<',true),1);
}
Just Lucky Really
  • 1,341
  • 1
  • 15
  • 38