使用CSV中的preg_replace删除LF

时间:2017-03-03 10:44:12

标签: php regex preg-replace

我尝试使用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"之后的换行符。

谢谢!

1 个答案:

答案 0 :(得分:0)

^\|(.*)\n(.*)\|$模式匹配字符串start处的|,然后匹配换行符之外的任何0+字符\n,除了换行符之外的任何0+字符和{ {1}}在字符串的末尾。所以,基本上,你用代码清空这些字符串,而不是只删除换行符号。

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

preg_replace_callback

请参阅PHP demo