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.
$string="123456789";
$format=['XXX','XX','XXXX'];
$formatted="";
foreach ($format as $cluster){
$formattedCluster=substr($string,0,strlen($cluster));
$string=substr($string,strlen($cluster));
$formatted.=$formattedCluster.' ';
}
$formatted=substr($formatted, 0, -1);
dd($formatted);
//outputs: "123 45 6789"
As you can see it takes a string without any whitespace, and separates it with whitespaces according to a pattern $format
in this case. The pattern is an array.
A pseudo example:
$str='qweasdzxc'
$pattern=['X','X','XXXX','XXX']
$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.
Environment: Php 7.4, Laravel 8
I would use https://www.php.net/manual/en/function.vsprintf.php do get the result:
$str='qweasdzxc';
$pattern='% % %%%% %%%'; // ['X','X','XXXX','XXX']
echo vsprintf(str_replace('%', '%s', $pattern), str_split($str));