dongmu6225 2014-08-14 13:33
浏览 26
已采纳

PHP从一个大段落替换小段落中的行

I have 2 bulks of text: Trunk, and Card. Trunk has about 100 lines, and Card has 3. The 3 lines in Card exist in Trunk, but they aren't directly below eachother.

What I'm trying to do is remove each line of Card from the string Trunk.

What came to mind is exploding Card into an Array and using a for each in loop, like in AS3, but that didn't work like planned. Here's my attempt:

$zarray = explode("
", $card); //Exploding the 3 lines which were seperated by linebreaks into an array

foreach ($zarray as $oneCard) //for each element of array
{
    $oneCard.= "
"; //add a linebreak at the end, so that when the text is removed from Trunk, there won't be an empty line in it.
    print "$oneCard stuff"; //Strangely outputs all 3 elements of the array seperated by , instead of just 1, like this:
    //card1card2card3 stuff
    $zard = preg_replace("/$oneCard/i", "", $trunx, 1);//removes the line in Card from Trunk, case insensitive.
    $trunx = $zard; //Trunk should now be one line shorter.
}

So, how can I use the foreach loop so that it replaces properly, and uses 1 element each time, instead of all of them in one go?

  • 写回答

3条回答 默认 最新

  • doujiejujixi27244 2014-08-14 13:39
    关注

    Consider

    $trunk = "
    a
    b
    c
    d
    e
    f
    ";
    
    $card = "
    c
    e
    a
    ";
    
    
    $newtrunk = implode("
    ", array_diff(
        explode("
    ", $trunk),
        explode("
    ", $card)
    ));
    print $newtrunk; // b d f
    

    Or the other way round, your wording is a bit unclear.

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

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程