我尝试用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“之后的换行符。
谢谢!
发布于 2017-03-03 18:58:30
^\|(.*)\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。
https://stackoverflow.com/questions/42576768
复制相似问题