line break inside the string

Asked

Viewed 6,032 times

0

How to insert line break into 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


    ?> 
  • 2

    I believe it is not possible because space and contact as a character, what is your goal with this ?

  • @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.

4 answers

4

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, ' ' ] );

0

Try

    <?php 

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

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


?> 

0

You’ve tested it like this:

<?php 
        $str = "Vou para Manaus";               
        echo(strlen($str)); //exibe 15
        $str = "Vou para" . PHP_EOL . "Manaus";                
        echo(strlen($str)); //exibe 18
?>

A line break PHP constant that fits according to the operating system.

-5

try like this

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.