First, be aware of the difference between characters and bytes.
The function strlen()
returns quantity in bytes.
If you 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 get to the point?
count the number of characters 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.
Playing a little longer, 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, ' ' ] );
I believe it is not possible because space and contact as a character, what is your goal with this ?
– Gabriel Rodrigues
@Gabriel, it’s common to have that kind of rule in a business model. For example, count how many characters were typed in a text, but ignore spacing count, line breaks, and scores. In a practical example, a text translation service where the translation price is based on the amount of characters. It would be unfair to charge for spaces and line breaks.
– Daniel Omine