在数字之间添加字符

I have an integer $client_version=1000 I do need to add dots between every number in this integer so it looks like 1.0.0.0 and save it in new variable as string.

How can I do this?

  • PHP offers the function array str_split ( string $string [, int $split_length = 1 ] ) to convert a string to a character-array or blocks of characters. In your case, invoking str_split((string)1000, 1) or str_split((string)1000) will result in:

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

    Code:

    implode('.',str_split((string)1000))
    

    Result: 1.0.0.0


  • For a more general, yet less well known approach, based on Regular Expression see this gist and this tangentially related topic on SO.

    Code:

    preg_match_all('/(.{1})/', (string)1000, $matches);
    echo implode('.', $matches[0]);
    

    Result: 1.0.0.0

Easy enough:

$client_version = 1000; 
$dotted = join(".",str_split($client_version));

Note that this will always split it so that there is only one character between the dots. If you want something like 1.00.0, you'll need to change your question to explain more about what you're trying to do and what patterns you need.

Use str_split to get an array of chars and then implode them.

$client_version = 1000;
$client_version_chars = str_split($client_version);
$client_version_with_dots = implode('.', $client_version_chars);