Php 用模式格式化字符串

Php format string with pattern

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

    $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

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

环境: Php7.4, Laravel 8

$string = "qweasdzxc";
$chunks = array(1,1,4,3);
// Optional check to ensure that $string can be divided into requested chunks
if(array_sum($chunks) <> strlen($string)) { 
    echo "String length does not fit requested chunks.";
}
$i=0;
$output = "";
foreach($chunks as $chunk) { 
    $output .= substr($string,$i,$chunk) . " ";
    $i += $chunk;
}

echo rtrim($output);
// Outputs "q w easd zxc"

根据它是否是数组的最后一个元素,不首先添加它,这可能是从右端删除空格的更简单方法,但这确实有效。

我会使用 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));

简单易用preg_match试试这个。

$data = '11234567890';

if(preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $data,  $matches))
{
    $result = $matches[1] . ' ' .$matches[2] . ' ' . $matches[3];
    echo  $result;
}

我认为这不是您所期望的,但是:

function format_number($number) {
    $number_size = strlen($number);
    
    if (9 != $number_size) {
        return $number;
    }
    
    $step     = 0;
    $formated = '';
    foreach (range(0, 9) as $i => $n) {
        if (isset($number[$n])) {
            switch ($step) {
                case 0:
                case 1:
                case 3:
                case 5:
                case 6:
                case 7:
                case 8:
                    $formated .= $number[$n];
                    break;
                case 2:
                case 4:
                    $formated .= $number[$n] . ' ';
                    break;
            }   
            $step++;
        }
    }
    
    return $formated;
}

仅适用于模式 XXX XX XXXX