首页 文章

在CSV中使用preg_replace删除LF

提问于
浏览
1

我尝试使用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

    ^\|(.*)\n(.*)\|$ 模式匹配字符串start处的 | ,然后是换行符以外的任何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 .

相关问题