2

I have string number:

$number = "101011004113511113";

And I need to convert this to format like:

$pattern = "10 101 1004 1135 11113";

I have succeed that with this code:

<?php

    $number = "101011004113511113";

    $pattern = "10 101 1004 1135 11113";

    $newNumber = "";

    for ($i = 0; $i < strlen($number); $i++)
    {
        if ($i == 2)
        {
            $newNumber .= " ";
        }

        if ($i == 5)
        {
            $newNumber .= " ";
        }

        if ($i == 9)
        {
            $newNumber .= " ";
        }

        if ($i == 13)
        {
            $newNumber .= " ";
        }

        $newNumber .= $number[$i];
    }

    echo $newNumber;

I would like to know is there a better programming solution for this problem. As I currently learning programming I would like opinion of a experienced programmer, is some better programming solution even necessary.

5
  • 4
    what's the rule here ? Commented Mar 22, 2019 at 15:31
  • Are the spaces at fixed indexes? Or is there another rule? Commented Mar 22, 2019 at 15:32
  • I mean, there is no special rule, I have this number and the rule is ad space like in $pattern. Commented Mar 22, 2019 at 15:33
  • That is why I am thinking that there is no better solution for this problem. Commented Mar 22, 2019 at 15:33
  • If you already know what you want the end result to look like, why even bother with this? $newNumber = $pattern; no? Commented Mar 22, 2019 at 15:35

1 Answer 1

2

You can use a regex pattern to capture the count of numbers you want and then join them by a space:

preg_match('/(\d{2})(\d{3})(\d{4})(\d{5})/',$number, $result);
$result = implode(' ', array_slice($result, 1));

This is only the second question where I get to use vsprintf:

$result = vsprintf("%d%d %d%d%d %d%d%d%d %d%d%d%d%d", str_split($number));
Sign up to request clarification or add additional context in comments.

3 Comments

may be the pattern is not steady . it's not generic i think
I think this is great, the pattern is the same, if they change, I can easily adopt this regex.Nice work.
Added an alternative, might be easier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.