0

I know about ^ and $, but I want to remove the last empty row of a string, not each.

$s = 'Foo

Bar

Baz
';

should return as

$s = 'Foo

Bar

Baz;

How could it be done in PHP with regex?

You can try it here: http://codepad.viper-7.com/p3muA9

2
  • 2
    Why not simply use rtrim() rather than more complex regexp?
    – Mark Baker
    May 5, 2012 at 10:50
  • actually he can use rtrim() to strip whitespace from the end of the string. May 5, 2012 at 10:52

3 Answers 3

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;

?>

Use rtrim().

0
1

Use:

$s_replaced = preg_replace("/".PHP_EOL."$/", '', $s);
1
  • You must have the magical view to know the row-ending TS writes about. And for which operating system have you written the code specifically?
    – hakre
    May 5, 2012 at 11:03
0

Try this:

Find with:

(?s)\s+$

Replace with:

none

Explanation:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.