Home > Software engineering >  Split text into equal-sized variables
Split text into equal-sized variables

Time:08-26

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?

CodePudding user response:

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.
)

CodePudding user response:

The existing functions str_split and chunk_split can be used to split a string into smaller chunks, however these take the chunk length as an argument.

You can work that out and pass it through just fine in either case.

chunk_split requires extra processing and requires a "special" character that is never used in the text so that you can use explode afterwards and turn into an array.

str_split doesn't require a special character. I've created an example function below which uses this function and does a small amount of processing beforehand so that you don't need to repeat it each time (just use the function).

$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.";

function auto_str_split($input, $num_chunks = 4) {
    $length = strlen($input);
    // determine the size of each chunk
    // the last chunk may be shorter whenever
    //   $length is a not multiple of $num_chunks
    $chunk_size = ceil($length / $num_chunks);

    return str_split($input, $chunk_size);
}

echo json_encode(auto_str_split($text, 4), JSON_PRETTY_PRINT);

Outputs

[
    "It is a long established fact t",
    "hat a reader will be distracted",
    " by the readable content of a p",
    "age when looking at its layout."
]
  • Related