首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在CSV中使用preg_replace删除LF

在CSV中使用preg_replace删除LF
EN

Stack Overflow用户
提问于 2017-03-03 18:44:12
回答 1查看 207关注 0票数 1

我尝试用PHP preg_replace删除CSV文件中的一些换行符。我还是不明白。我试了很多。也许有人能帮我写代码。

代码语言:javascript
复制
$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“之后的换行符。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-03 18:58:30

^\|(.*)\n(.*)\|$模式匹配字符串开头的|,然后匹配除换行符以外的任何0+字符,匹配\n,再匹配除换行符以外的任何0+字符,最后匹配字符串末尾的|。因此,基本上,您可以使用代码清空这样的字符串,而不是只删除换行符。

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

代码语言:javascript
复制
$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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42576768

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档