Michael Ng
Michael Ng

Reputation: 33

Split a string into smaller string by length

I am really new to PHP and I am trying split a string into a smaller string by a length, and then it returns an array of these small strings.

here is what I got so far:

    <?php

        $str = $_POST['input']; //It will get the string from the input
        $string = str_split($str, 4);

    for ($i=0; $i <strlen($str); $i++) { 
        $string[$i] = str_split($str,4);
    }

    ?>

<td>Output:</td>
<td align="center"><textarea rows="5" cols="50" readonly="readonly"><?php echo $string[$i]."\n"; ?></textarea></td>

Can anybody show me how can I return an array of the strings by length of 4? Thank you so much.

Upvotes: 2

Views: 695

Answers (1)

Noor Ahmed
Noor Ahmed

Reputation: 1617

You are doing it right. Just return after str_split

    $str = $_POST['input']; //It will get the string from the input
    $string = str_split($str, 4);  // this is a array of strings with lenght 4
    return $string; 

The $string variable has the following structure:

Array
(
    [0] => Hell
    [1] => oFri
    [2] => day
)

Upvotes: 1

Related Questions