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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?