在大写字符上分解字符串?

gre*_*emo 14 php string

何我可以根据大写字符将$param字符串分解$chunks成碎片?

$string = 'setIfUnmodifiedSince';
$method = substr($string, 0, 3);
$param  = substr($string, 3);

// Split $param and implode with '-' separator
$chunks = splitAtUpperCase($param); // Chunks are: 'If', 'Unmodified' and 'Since'
$field  = implode('-', $chunks); // Get If-Unmodified-Since HTTP field name
Run Code Online (Sandbox Code Playgroud)

jen*_*ram 35

使用preg_split()on [A-Z]应该做:

function splitAtUpperCase($s) {
        return preg_split('/(?=[A-Z])/', $s, -1, PREG_SPLIT_NO_EMPTY);
}
Run Code Online (Sandbox Code Playgroud)

编辑
如果您不需要数组本身,您可以使用连字符(-)预先校正大写字符(第一个除外):

preg_replace('/(?<!^)([A-Z])/', '-\\1', $param);
Run Code Online (Sandbox Code Playgroud)

(演示)


JRL*_*JRL 5

$chunks = preg_split('/(?=[A-Z])/', $string);
Run Code Online (Sandbox Code Playgroud)