ven
ven

Reputation: 405

How to do a loop (foreach) in PHP

I am trying to scrape some strings (colors in the example below) but can only manage to scrape the first string (blue):

<?php

   function extract_unit($string, $start, $end)
   {
      $pos = stripos($string, $start);

      $str = substr($string, $pos);

      $str_two = substr($str, strlen($start));

      $second_pos = stripos($str_two, $end);

      $str_three = substr($str_two, 0, $second_pos);

      $unit = trim($str_three); // remove whitespaces

      return $unit;
    }   


// example to extract the colors 

$text = '<p>this is the color blue</p><p>this is the color yellow</p><p>this is the color red</p>';
$unit = extract_unit($text, 'color', '</p>');

// Outputs: blue, but I need yellow and red as well!
echo $unit;
?>

The above works but only outputs: blue, but I need yellow and red as well!

 foreach( $unit as $item )
{
    echo $item.'<br />';
}

This did not work, any ideas? Thanks!

Upvotes: 0

Views: 68

Answers (3)

Mauricio Villanueva
Mauricio Villanueva

Reputation: 1

To use the foreach method, you need to have an array. The way to declare an array in php is:

$array = array("blue", "green", "yellow");

So your function will have to return an array, not a simple variable.

Hint: var_dump($array) function helps a lot in php for debugging.

Upvotes: 0

check
check

Reputation: 559

this answer based on your logic.

function extract_unit($haystack, $keyword1, $keyword2){
    $return = array();
    $a=0;
    while($a = strpos($haystack, $keyword1, $a)){   // loop until $a is FALSE
        $a+=strlen($keyword1);                    // set offset to after $keyword1 word
        if($b = strpos($haystack, $keyword2, $a)){  // if found $keyword2 position's
            $return[] = trim(substr($haystack, $a, $b-$a)); // put result to $return array
        }
    }
    return $return;
}

$text = '<p>this is the color blue</p><p>this is the color yellow</p><p>this is the color red</p>';
$unit = extract_unit($text, 'color', '</p>');
print_r($unit);

Upvotes: 0

Axiom
Axiom

Reputation: 902

From what I understand, you want to go through some HTML and grab each item inside of the <p> tags, and take what's after color to grab the specific word.

This is specifically for this situation but could easily be changed.

$text = '<p>this is the color blue</p><p>this is the color yellow</p><p>this is the color red</p>';
$unit = explode("<p>",$text); //Use PHP explode function
foreach($unit as $item){
  if($item != ""){ //If it's not empty
    $item = explode("color",$item); //explode() creates array
    $item = end($item); //Grab last element of array
    $item = trim($item); //Trim whitespace
    $item = strip_tags($item); //Remove the p tags
    echo $item."<br>"; //Echo out the color
  }
}

More info on PHP Explode: http://php.net/manual/en/function.explode.php

Upvotes: 1

Related Questions