在 CSV 中删除带有 preg_replace 的 LF

Remove LF with preg_replace within CSV

我尝试使用 PHP preg_replace 删除 CSV 文件中的一些换行符。 我不明白。我试了很多。也许有人可以帮助我处理我的代码。

$content = "Halvah sweet ice.|Donut pastry candy canes bear claw toffee ice cream 
    cotton candy jelly-o. Pastry chocolate lemon drops biscuit muffin muffin apple pie croissant. Candy canes topping pudding biscuit. Cotton candy sweet mi bears chocolate. Croissant sesame snaps chocolate cake. Topping toffee oat cake cake. Biscuit| cheesecake powder";

$content = preg_replace('/^\|(.*)\n(.*)\|$/', "", $content);

// expected result
$content = "Halvah sweet ice.|Donut pastry candy canes bear claw toffee ice cream cotton candy jelly-o. Pastry chocolate lemon drops biscuit muffin muffin apple pie croissant. Candy canes topping pudding biscuit. Cotton candy sweet mi bears chocolate. Croissant sesame snaps chocolate cake. Topping toffee oat cake cake. Biscuit| cheesecake powder";

它应该只删除 | 之间的换行符|,例如,单词 "cream".

后的换行符

谢谢!

^\|(.*)\n(.*)\|$ 模式匹配字符串开头的 |,然后是换行符以外的任何 0+ 个字符,\n,再次是换行符以外的任何 0+ 个字符,并且字符串末尾的 |。所以,基本上,你用代码清空这些字符串,而不是只删除换行符。

您可以在 preg_replace_callback 函数中使用简单的 \|[^|]+\| 正则表达式来匹配所有 |...| 子字符串并一次性删除其中的多个换行符:

$content = preg_replace_callback("/\|[^|]*\|/", function($m) {
    return str_replace(array("\n", "\r"), "", $m[0]);
} , $content);
echo str_replace("\n", "NEWLINE", $content); // => Note there is no  NEWLINE in the output

参见PHP demo