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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题