首页 > 解决方案 > 带模式的php格式字符串

问题描述

我有一个字符串(修剪),我想根据预定义的模式拆分这个字符串。我写了一个可能更具解释性的代码。

    $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"

如您所见,它接受一个没有任何空格的字符串,并$format在这种情况下根据模式将其用空格分隔。该模式是一个数组。

一个伪例子:

$str='qweasdzxc'

$pattern=['X','X','XXXX','XXX']

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

它按预期工作,但相当可怕。这个问题的正确解决方案是什么?正确性是指速度和可读性。

环境:PHP 7.4,Laravel 8

标签: phplaravelstringphp-7

解决方案


我会使用https://www.php.net/manual/en/function.vsprintf.php得到结果:

$str='qweasdzxc';
$pattern='% % %%%% %%%'; // ['X','X','XXXX','XXX']
echo vsprintf(str_replace('%', '%s', $pattern), str_split($str));

推荐阅读