剥去一个字符串的最后一行空行?

时间:2012-05-05 10:42:59

标签: php regex

我知道^$,但我想删除字符串的最后一个空行,而不是每个。

$s = 'Foo

Bar

Baz
';

应该返回

$s = 'Foo

Bar

Baz;

如何使用正则表达式在PHP中完成?

您可以在此处试用:http://codepad.viper-7.com/p3muA9

3 个答案:

答案 0 :(得分: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()

答案 1 :(得分:1)

使用:

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

答案 2 :(得分:0)

试试这个:

查找:

(?s)\s+$

替换为:

none

<强>解释

<!--
(?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) «$»
-->