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

时间:2014-08-14 13:33:46

标签: php arrays string replace foreach

我有2个大量的文字:Trunk和Card。 Trunk有大约100行,Card有3行.Card中有3行存在于Trunk中,但它们不是直接在彼此之下。

我要做的是从字符串Trunk中删除每一行卡片。

我想到的是将Card扩展到一个数组并使用for each in循环,就像在AS3中一样,但这不像计划的那样工作。这是我的尝试:

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

foreach ($zarray as $oneCard) //for each element of array
{
    $oneCard.= "\n"; //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 \r, instead of just 1, like this:
    //card1\rcard2\rcard3 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.
}

那么,我如何使用foreach循环以使其正确替换,并且每次使用1个元素,而不是一次性使用所有元素?

3 个答案:

答案 0 :(得分:2)

考虑

$trunk = "
a
b
c
d
e
f
";

$card = "
c
e
a
";


$newtrunk = implode("\n", array_diff(
    explode("\n", $trunk),
    explode("\n", $card)
));
print $newtrunk; // b d f

或者反过来说,你的措辞有点不清楚。

答案 1 :(得分:0)

试试这个,由于替换量很小,它会比preg_replace更快:

//Find the new lines and add a delimiter
$card = str_replace("\n", "\n|#|", $card);

//Explode at the delimiter
$replaceParts = explode('|#|', $card);

//Perform the replacement with str_replace and use the array
$text = str_replace($replaceParts, '', $text);

这假设在搜索部分之后总是有换行符,并且您不关心区分大小写。

如果您不了解新行,则需要一个带有可选匹配项的正则表达式。

如果您需要区分大小写,请查看str_ireplace

答案 2 :(得分:0)

你可以爆炸$ card,并将$ trunk保持为字符串:

$needlearray = explode("\n", $card); //to generate the needle-array
$trunk = str_replace($needlearray,array(),$trunk); //replace the needle array by an empty array => replace by an empty string (according to the str_replace manual)
$trunk = str_replace("\n\n","\n",$trunk); //replace adjacent line breaks by only one line break