Reputation: 31
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?
Upvotes: 1
Views: 223
Reputation: 47883
For the simple matter of injecting a dot between every character, you can use preg_replace()
and target each zero-width position which is not the start or end of the string.
Code: (Demo)
$client_version = 1000;
echo preg_replace(
'/(?!^|$)/',
'.',
$client_version
);
// 1.0.0.0
As others have warned, using an integer as the version number will become unusable when individual integers require more than one digit.
Upvotes: 0
Reputation: 24710
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
Upvotes: 1
Reputation: 10153
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);
Upvotes: 0
Reputation: 3592
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.
Upvotes: 3