2017-03-03 5 views
1

PHP preg_replaceを使用してCSVファイル内の改行を削除しようとしました。 私はそれを取得しません。私はたくさん試しました。誰かが私のコードを手伝ってくれるかもしれません。CSV内のpreg_replaceでLFを削除

$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"; 

|例えば、 "クリーム"という単語の後の改行。

ありがとうございます!

+0

注意:* preg_replace():行6の/home/kVVTYTY/prog.phpで未知の修飾語 '\'が表示される* –

+1

['$ content = preg_replace_callback("/\ | ($ m){\t return str_replace(配列( "\ n"、 "\ r")、 ""、$ m [0]); }、$ content) ; '](https://ideone.com/J0tdns)。 –

+0

@WiktorStribiżewあなたが正しいです、私は古いコードバージョンを使用しました。私はスタックで/ \\\\ n /というサンプルを見つけました。そして、\ nが正しいかどうかをエスケープするようにしました。 – vine

答えて

0

^\|(.*)\n(.*)\|$パターンは、文字列の開始時|と一致再度改行、\n、改行以外の任意の0+文字と文字列の末尾|以外の任意の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を参照してください。

+1

それは動作します!ありがとう。 – vine

関連する問題