Php format string with pattern

  laravel, php, php-7, string

I have a string (trimmed) and i would like to split this string according to a predefined pattern. I wrote a code which is probably more interpretive.

        foreach ($format as $cluster){
            $formatted.=$formattedCluster.' ';
        $formatted=substr($formatted, 0, -1);

//outputs: "123 45 6789"

As you can see; it takes a string without any whitespace, and separates it with withspaces according to a pattern $format in this case. Pattern is a array.

A pseudo example:



$formatted='q w easd zxc'; //expected output

It works as expected but it is rather hideous. What is the correct solution to this problem ? By correctness, i mean speed and readability.

Thank you.

Php 7.4,
Laravel 8

Source: Laravel

Leave a Reply