2012-05-05 1 views
0

私は約^$を知っていますが、文字列の最後の空の行を削除する必要があります。それは正規表現とPHPで行うことができる方法文字列の最後の空の行を削除しますか?

$s = 'Foo 

Bar 

Baz; 

として

$s = 'Foo 

Bar 

Baz 
'; 

を返す必要がありますか?

あなたはここでそれを試すことができます。http://codepad.viper-7.com/p3muA9

+2

はなぜ、より複雑な正規表現ではなく)(RTRIMを使用するだけではありませんか? –

+0

実際には 'rtrim()'を使って文字列の最後から空白を取り除くことができます。 –

答えて

3
<?php 

$s = 'Foo 

Bar 

Baz 
'; 

$s_replaced = preg_replace('//', '', $s); 

$s_replaced = rtrim($s_replaced); 
$out = '<textarea cols=30 rows=10>'.$s_replaced.'</textarea>'; 

echo $out; 

?> 

使用rtrim()

+0

ああ、ありがとう、私は正規表現に焦点を当てて盲目的だった。 – Martin

+0

問題ありません:)あなたと仕事をしている場合はそれを受け入れてください:) –

1

用途:

$s_replaced = preg_replace("/".PHP_EOL."$/", '', $s); 
+0

行末のTS書き込みについて知るには、魔法のようなビューが必要です。どのオペレーティングシステムでコードを具体的に記述していますか? – hakre

0

これを試してみてください:

をして下さい:

(?s)\s+$ 

と交換

説明:

<!-- 
(?s)\s+$ 

Options: case insensitive;^and $ match at line breaks 

Match the remainder of the regex with the options: dot matches newline (s) «(?s)» 
Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s+» 
    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
Assert position at the end of a line (at the end of the string or before a line break character) «$» 
--> 
関連する問題