Martin
Martin

Reputation: 2017

Strip last empty row of a string?

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

Upvotes: 0

Views: 81

Answers (3)

codaddict
codaddict

Reputation: 455152

Use:

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

Upvotes: 1

Cylian
Cylian

Reputation: 11182

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

Upvotes: 0

Ahmed Jolani
Ahmed Jolani

Reputation: 3082

<?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().

Upvotes: 3

Related Questions