PHP用大段落替换小段落中的行


PHP replacing lines in a small paragraph from a big paragraph

我有两大块文本:Trunk和Card。Trunk大约有100条线路,Card有3条。Card中的3行存在于Trunk中,但它们并不在彼此的正下方。

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

我想到的是将Card扩展为Array并使用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循环,以便它正确地替换,每次使用一个元素,而不是一次使用所有元素?

考虑

$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

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

试试这个,它将比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

您可以将$卡片爆炸,并将$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