Search code examples
phpvariables

Split text into equal-sized variables


How could I divide the value of a variable by 4. Dividing according to the number of characters.

$text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.";

In the example above I would divide by 4, and it would be 31 characters for each variable. Is there any way I can reproduce this type of result automatically regardless of the content of the $text variable?


Solution

  • Another solution is to:

    $string = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.";
    $string_length = strlen($string);
    $chunks = 4; // change to desired.
    $parts = ceil($string_length / $chunks); // Break string into the 4 parts.
    $str_chunks = chunk_split($string, $parts);
    
    $string_array = array_filter(explode(PHP_EOL, $str_chunks));
    print_r($string_array);
    

    Output:

    Array
    (
        [0] => It is a long established fact t
        [1] => hat a reader will be distracted
        [2] =>  by the readable content of a p
        [3] => age when looking at its layout.
    )