0

I know this has been asked before @ this post, but I am trying to strip empty lines at the end as well.

I am using:

function removeEmptyLines($string)
{
return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $string);
}

Which works great in any combination but:

 aadasdadadsad
 adsadasdasdas
 (empty line here)

I'm attempting to do a count() on the returned array, but since it is replacing the \n with a \n\, it's not working. I tried a few other examples in the above post, but none have worked.

My other function (so far)

function checkEmails($value) {

$value = removeEmptyLines($value);

$data = explode("\n", $value);
$count = count($data);

return $count;

 }

Basically it's a form's text-area posting to itself and if someone hits enter after the a full line, it still counts the blank line.

Any help would be much appreciated,

Thanks!

Tre

Community
  • 1
  • 1
tr3online
  • 1,429
  • 2
  • 24
  • 45

3 Answers3

2

PHP's trim function does this by default:

$string = trim($string);

You can also use either ltrim() or rtrim() if you only want to strip from the start or end of the string.

Tim Fountain
  • 33,093
  • 5
  • 41
  • 69
1

Try:

preg_replace('/^[\r\n]+|[\r\n]+$/m', '', $string);

See it working

If you want to strip leading/trailing whitespace from the lines as well, replace the two occurences of [\r\n] with \s. Note also that the fact I have single-quoted the expression string is important.

DaveRandom
  • 87,921
  • 11
  • 154
  • 174
0

You can instead use

rtrim($string, "\n");
Wouter Dorgelo
  • 11,770
  • 11
  • 62
  • 80
Mukesh Soni
  • 6,646
  • 3
  • 30
  • 37
  • You can't single quote \n, so this will only work if you double quote it instead. And the code in the question is stripping more chars than just \n – Tim Fountain May 30 '12 at 10:51