dsafq2131321 2015-11-03 02:45
浏览 36
已采纳

如何在PHP中执行循环(foreach)

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!

  • 写回答

3条回答 默认 最新

  • dongxing8650 2015-11-03 03:36
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)