Reputation: 27628
How would I remove a line from the end of a string with PHP? Thanks.
Upvotes: 0
Views: 2167
Reputation: 1367
$subject = 'Text
written
with
lines';
echo preg_replace('/\\n[^\\n]*\\n?$/', '', $subject);
With feature, that there can be one special newline at the end which is ignored, 'cause it is often a good convention to let one at the end of a file (assuming you are reading string from a file).
Upvotes: 0
Reputation: 405
if you're trying to remove a line from an end of a file, you could try using PHP's file() function to read the file (which places it into an array) and then pop the last element. This is assuming that php is recognizing the line endings in your file.
Upvotes: 0
Reputation: 6258
If you are looking to remove the last line is a string containing new line character (\n), then you'd do something like this ...
$someString = "This is a test\nAnd Another Test\nAnd another test.";
echo "SomeString BEFORE=".$someString."\n";
// find the position of the last occurrence of a \n
$firstN = strlen($someString) - strpos(strrev($someString), "\n");
// get rid of the last line
$someString = substr($someString, 0, $firstN);
echo "SomeString AFTER=".$someString;
Upvotes: 0
Reputation: 4682
You want to remove whitespace? Try trim()
. It's close cousins ltrim
and rtrim
may be closer to what you want.
Upvotes: 5