Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

You can instead use

rtrim($string, "\n");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top