break line inside string

0

How to insert line break in a string, without increasing the number of characters?

    <?php 

        $str = "Vou para Manaus";               
        echo(strlen($str)); //exibe 15

        $str = "Vou para
        Manaus";                
        echo(strlen($str)); //exibe 18


    ?> 
    
asked by anonymous 02.09.2015 / 22:48

3 answers

4

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, ' ' ] );
    
03.09.2015 / 00:25
0

Try

    <?php 

    $str = "Vou para Manaus";               
    echo(strlen($str)); //exibe 15

    $str = "Vou para \n Manaus";                
    echo(strlen($str)); //exibe 18


?> 
    
02.09.2015 / 23:03
-5

Try this

$str = "Vou para "\n" Manaus";                
echo(strlen($str)); //exibe 18
    
02.09.2015 / 23:54