duanmei1536 2016-01-11 17:11
浏览 13
已采纳

php foreach显示旧段

I have created a script where every other word in a paragraph is green, which is correct. However there is a problem because the original paragraph which I used appears above the new paragraph, which I do not want.

This solution to this may be simple but I can't get my head around it.

Can anyone point me in the right direction?

Code:

    <?php
$storyOfTheDay= "Once upon a time there was an old woman who loved baking gingerbread. She would bake gingerbread cookies, cakes, houses and gingerbread people, all decorated with chocolate and peppermint, caramel candies and colored frosting.

She lived with her husband on a farm at the edge of town. The sweet spicy smell of gingerbread brought children skipping and running to see what would be offered that day.

Unfortunately the children gobbled up the treats so fast that the old woman had a hard time keeping her supply of flour and spices to continue making the batches of gingerbread. Sometimes she suspected little hands of having reached through her kitchen window because gingerbread pieces and cookies would disappear.";

$storyOfTheDay = preg_split("/\s+/", $storyOfTheDay);

//Adding <span> to odd array index items
foreach (array_chunk($storyOfTheDay , 2) as $chunk) {
$storyOfTheDay[] = $chunk[0];
    if(!empty( $chunk[1]))
    {
       $storyOfTheDay[] = $chunk[1]= "<span style='color:green'>". $chunk[1] ."</span>";

    }
}


$storyOfTheDay = join(" ", $storyOfTheDay);

echo $storyOfTheDay;

Output:

Image of Output

  • 写回答

1条回答 默认 最新

  • doutongxuan1614 2016-01-11 17:57
    关注

    You are continuously filling the same array ($storyOfTheDay). Make the new one:

    $storyOfTheDay = preg_split("/\s+/", $storyOfTheDay);
    
    $newStoryOfTheDay = [];
    //Adding <span> to odd array index items
    foreach (array_chunk($storyOfTheDay , 2) as $chunk) {
        $newStoryOfTheDay[] = $chunk[0];
        if( !empty($chunk[1]) ){
           $newStoryOfTheDay[] = "<span style='color:green'>". $chunk[1] ."</span>";
        }
    }
    
    $newStoryOfTheDay = join(" ", $newStoryOfTheDay);
    echo $newStoryOfTheDay;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型