php - Divide the string into parts and convert it to an array

537

It is necessary to split the string every 500 symbols, and put every part into array.

Example:

$str = "xx...xxxx" (1550 symbols)

Result:

array(4) {
  [0]=>
  string(500) "xxx.xx"
  [1]=>
  string(500) "xxx.xx"
  [2]=>
  string(500) "xxx.xx"
  [3]=>
  string(50) "xxx.xx"
}

Tried this way, but this is not what I need:

$arr = str_split($str,500);

How to solve this problem in the best way?

Thnx!

578

Answer

Solution:

Here is solution for me

function split($str, $len = 1) {
    $arr    = [];
    $length   = mb_strlen($str, 'UTF-8');
    for ($i = 0; $i < $length; $i += $len) {
        $arr[] = mb_substr($str, $i, $len, 'UTF-8');
    }
    return $arr;
}
$arr = split($cart,55);

u_mulder, thanx for the hint with UTF encoding:)

People are also looking for solutions to the problem: php - how to write an individual error_log for each file

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.