First, be aware of the difference between characters and bytes.
The function strlen()
returns amount in bytes.
CAso want to count the number of characters, use the function mb_strlen()
$str = "Vou para Maranhão";
echo strlen($str); //exibe 18
echo mb_strlen($str); //exibe 17
Let's go to the main point?
count the number of characters by ignoring line breaks:
$str = "Vou para
Maranhão";
$l = mb_strlen( str_replace("
",'',$str) );
echo PHP_EOL . $l; //exibe 17
The idea is simple. Just remove unwanted characters before counting.
By playing a bit more, we can create a function:
$str = "Vou para
Maranhão";
/**
No segundo parâmetro, indique os caracteres que dseja ignorar. O argumento recebe 'string' ou 'array'
*/
function mb_strlen2( $str, $ignore = null )
{
return mb_strlen( str_replace($ignore,'',$str) );
}
/*
Ignora quebras de linha
*/
echo PHP_EOL . '<br />' . mb_strlen2( $str, PHP_EOL );
/*
Ignora quebras de linha e espaçamentos
*/
echo PHP_EOL . '<br />' . mb_strlen2( $str, [ PHP_EOL, ' ' ] );