Divide a sentence into 2

Asked

Viewed 190 times

3

In PHP I get a phrase from the database, example: Nome do produto teste cadastrado no banco

I need to split her in two like this:

Nome do produto teste
cadastrado no banco

I mean, as much as half as possible, how do you do that? I tried counting the characters and splitting them in half, but you end up cutting a word in half, like this:

$nomeProd = "Nome do produto teste cadastrado no banco";
$nomeCaracter = (strlen($nomeProd))/2;
$nome1 = substr($nomeProd, 0, $nomeCaracter);
$nome2 = substr($nomeProd, $nomeCaracter);
echo $nome1;
echo "<br>";
echo $nome2;

The result was this:

Nome do produto test
e cadastrado no banco

Notice that the word teste separate, and this could not occur.

  • a solution would be to count the spaces and divide the sentence in the middle space

  • But you end up cutting a word in half....

  • take a look at the function substr() :http://php.net/manual/en/function.substr.php

  • I explained the difficulty better @Thiagodrulla

4 answers

4

Dude, it should be simpler. But I think it works. I didn’t test it 'cause there’s no way now.

$frase = "Nome do produto teste cadastrado";

function divide($frase) {

    $quebra = explode(" ", $frase);
    $meio = count($quebra)/2;
    $parte = "";

    foreach($quebra as $k => $v) {

        if ($k <= $meio) {

            $parte[0] .= $v . " ";

        } else {

            $parte[1] .= $v . " ";  
        }

    }

    return $parte;
}


$p = divide($frase);

echo $p[0] . "<br>" . $p[1];

4


A very basic solution:

<?php    
    $frase = 'Nome do produto teste cadastrado';
    $partes = explode(' ', $frase);
    $quant = count($partes);
    $div = ceil($quant / 2);
    $items = array_chunk($partes, $div);

    foreach($items as $item)
    {
        echo implode(' ', $item);
        echo PHP_EOL;
    }

Take the phrase and extract in parts by the blank space factor, the amount of items in this array divides by 2 and if there is broken value up, then use arra_chunk for the division of array in two parts and then just print the values with implode.

I believe this can help you put in your code by making an adaptation and this online example can verify the generation of information.


A function can be created and split that phrase as you wish:

<?php

    $frase = 'Nome do produto teste cadastrado';
    $count_itens = 2;

    function dividir_texto($texto, $count_itens)
    {
        $array_retorno = array();
        if (!empty($texto))
        {
            $partes = explode(' ', $texto); 
            $div = ceil((count($partes)) / $count_itens);
            $items = array_chunk($partes, $div);
            foreach($items as $item)
            {
                $array_retorno[] = implode(' ', $item);
            }
        }
        return $array_retorno;
    }

    print_r(dividir_texto($frase, $count_itens));

with the following output:

Array
(
    [0] => Nome do produto
    [1] => teste cadastrado
)

and check out the online example

3

I believe that this solution is also valid

<?php

//Frase para dividir ao meio
$nomeProd = "Nome do produto teste cadastrado no banco";

//Quantidade de letras da frase
$comprimento = strlen($nomeProd);

//Obtem a metade da frase, e subtrai 1 para saber o indice da string (pois começa em 0)
$metade = (int) ceil($comprimento / 2) - 1;

//Caminha ate a metade ser um espaco em branco, assim nao quebra a palavra
$letra = $nomeProd[$metade];
while ($letra !== ' ') {
    $metade++;
    $letra = $nomeProd[$metade];
}

//Divide a string pela metade
$str1 = substr($nomeProd, 0, $metade);
$str2 = substr($nomeProd, ($metade + 1), $comprimento);

echo $str1 . PHP_EOL;
echo $str2 . PHP_EOL;

2

You can also use array_slice() (slice the array). The principle is the same: break the text in array, then count the size of the array and divide by 2. If the result is odd, the first part will be half the number of words +1 and the second part the rest. If it is even, obviously each part will have half of words.

$texto = "Nome do produto teste cadastrado no banco";

function divStr($string){
   $array = explode(" ", trim($string));
   $array_len = sizeof($array);
   $limite = $array_len%2 == 0 ? $array_len/2 : floor($array_len/2)+1;

   $texto1 = implode(" ", array_slice($array, 0, $limite));
   $texto2 = implode(" ", array_slice($array, $limite));

   return [$texto1, $texto2];
}

var_dump(divStr($texto));

Return:

array(2) {
  [0]=> string(21) "Nome do produto teste"
  [1]=> string(19) "cadastrado no banco"
}

Testing at Ideone

Browser other questions tagged

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