update page now
Laravel Live Japan

str_split

(PHP 5, PHP 7, PHP 8)

str_splitConverte uma string em um array

Descrição

str_split(string $string, int $length = 1): array

Converte uma string em um array.

Parâmetros

string

A string de entrada.

length

Comprimento máximo do pedaço.

Valor Retornado

Se o parâmetro opcional length for especificado, o array retornado será dividido em pedaços, sendo cada um deles com length de comprimento, exceto o pedaço final que pode ser mais curto se a string não for dividisível uniformemente. O length padrão é 1, o que significa que cada pedaço terá um byte de tamanho.

Erros/Exceções

Se length for menor que 1, uma exceção ValueError será lançada.

Registro de Alterações

Versão Descrição
8.2.0 Se string estiver vazio, um array agora é retornado. Anteriormente, um array contendo uma única string vazia foi retornada.
8.0.0 Se length for menor que 1, uma exceção ValueError será lançada agora; anteriormente, um erro de nível E_WARNING era gerado e a função retornava false.

Exemplos

Exemplo #1 Exemplos de uso de str_split()

<?php

$str
= "Tchau Amigos";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);

?>

O exemplo acima produzirá:

Array
(
    [0] => T
    [1] => c
    [2] => h
    [3] => a
    [4] => u
    [5] =>
    [6] => A
    [7] => m
    [8] => i
    [9] => g
    [10] => o
    [11] => s
)

Array
(
    [0] => Tch
    [1] => au
    [2] => Ami
    [3] => gos
)

Notas

Nota:

str_split() dividirá em bytes, em vez de caracteres, ao lidar com uma string codificada em múltiplos bytes. mb_str_split() pode ser usada para dividir a string em pontos de código. grapheme_str_split() pode ser usada para dividir a string em grupos de grafema.

Veja Também

adicionar nota

Notas de Usuários 1 note

up
7
Julian
2 years ago
The function str_split() is not 'aware' of words. Here is an adaptation of str_split() that is 'word-aware'.

<?php

$array =  str_split_word_aware(
    'In the beginning God created the heaven and the earth. And the earth was without form, and void; and darkness was upon the face of the deep.', 
    32
);

var_dump($array);

/**
  * This function is similar to str_split() but this function keeps words intact; it never splits through a word. 
  *
  * @return array<int, string>
  */
function str_split_word_aware(string $string, int $maxLengthOfLine): array
{
    if ($maxLengthOfLine <= 0) {
        throw new RuntimeException(sprintf('The function %s() must have a max length of line at least greater than one', __FUNCTION__));
    }
    
    $lines = [];
    $words = explode(' ', $string);

    $currentLine = '';
    $lineAccumulator = '';
    foreach ($words as $currentWord) {

        $currentWordWithSpace = sprintf('%s ', $currentWord);
        $lineAccumulator .= $currentWordWithSpace;
        if (strlen($lineAccumulator) < $maxLengthOfLine) {
            $currentLine = $lineAccumulator;
            continue;
        }

        $lines[] = $currentLine;

        / Overwrite the current line and accumulator with the current word
        $currentLine = $currentWordWithSpace;
        $lineAccumulator = $currentWordWithSpace;
    }

    if ($currentLine !== '') {
        $lines[] = $currentLine;
    }

    return $lines;
}

?>

OUTPUT: 

<?php

array(5) {
  [0]=> string(29) "In the beginning God created "
  [1]=> string(30) "the heaven and the earth. And "
  [2]=> string(28) "the earth was without form, "
  [3]=> string(27) "and void; and darkness was "
  [4]=> string(27) "upon the face of the deep. "
}

?>
To Top

Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!

Check out: eBank.nz (Art Generator) | Netwrck.com (AI Tools) | Text-Generator.io (AI API) | BitBank.nz (Crypto AI) | ReadingTime (Kids Reading) | RewordGame | BigMultiplayerChess | WebFiddle | How.nz | Helix AI Assistant