简体   繁体   中英

Preg_split creates an array, but makes it empty

I would like to split a line of 3 characters with a dot between them, that is, I have a value of 12345678, I want to get 12.345.678 from it, here is my code:

function insertDocs($str) {
    $str = str_split($str);
    $str = array_reverse($str);
    $str = implode($str);
    $str1 = preg_split("/[0-9]{1,3}/u", $str);
    print_r($str1);
    $str1 = implode('.', $str1);
    $str1 = str_split($str1);
    $str1 = array_reverse($str1);
    $str1 = implode($str1);
    return $str;
  }
  echo insertDocs("12345678");

Here is what I get in return:

Array
(
    [0] =>
    [1] =>
    [2] =>
    [3] =>
)

This is print_r, and echo:

87654321

Tell me what I'm doing wrong, or tell me how to make it easier, I will be very grateful to you

As your first part depends on the total number of characters, this code first splits off the odd bit from the start, then uses str_split() with the remainder to split it into 3 character segments...

function insertDocs($str) {
    $start = substr($str, 0, strlen($str) % 3);
    $end = str_split(substr($str, strlen($start)), 3);
    array_unshift($end, $start);
    return implode(".", $end);
}

So

echo insertDocs("12345678");

gives...

12.345.678

To fix your original code, you could change the preg_split() line to

$str1 = str_split($str, 3);

and make sure you return $str1 from the function and not $str .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM