phpday 2027 - Call for Papers

str_split

(PHP 5, PHP 7, PHP 8)

str_split — Converte una stringa in un array

Descrizione

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

Converte una stringa in un array.

Elenco dei parametri

string

La stringa di input.

length

Lunghezza massima di ciascun segmento.

Valori restituiti

Se viene specificato il parametro opzionale length, l'array restituito sarà suddiviso in segmenti, ciascuno di lunghezza length, tranne l'ultimo segmento che può essere più corto se la stringa non si divide in parti uguali. Il valore predefinito di length è 1, il che significa che ogni segmento avrà la dimensione di un byte.

Errori/Eccezioni

Se length è minore di 1, verrà lanciato un ValueError.

Log delle modifiche

Versione Descrizione
8.2.0 Se string è vuota, ora viene restituito un array vuoto. In precedenza veniva restituito un array contenente una singola stringa vuota.
8.0.0 Se length è minore di 1, ora verrà lanciato un ValueError; in precedenza, veniva invece emesso un errore di livello E_WARNING e la funzione restituiva false.

Esempi

Example #1 Esempi di uso di str_split()

<?php

$str = "Salve Amico!";

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

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

?>

Il precedente esempio visualizzerà:

Array
(
    [0] => S
    [1] => a
    [2] => l
    [3] => v
    [4] => e
    [5] =>
    [6] => A
    [7] => m
    [8] => i
    [9] => c
    [10] => o
    [11] => !
)

Array
(
    [0] => Sal
    [1] => ve
    [2] => Ami
    [3] => co!
)

Note

Nota:

str_split() divide in byte, anziché in caratteri, quando si tratta di una stringa con codifica multibyte. È possibile usare mb_str_split() per dividere la stringa in code point. È possibile usare grapheme_str_split() per dividere la stringa in cluster di grafemi.

Vedere anche:

User Contributed Notes 1 note

up
9
Julian
3 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. "
}

?>
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top