我需要拆分大写字母和数字,并在字符串中的任意位置将一系列大写字母拆分为整个单词。用示例解释可能最简单,请参阅下面的测试脚本:
$tests = array('FooBar', 'fooBar', 'Foobar', 'FooBar1', 'FooBAR', 'FooBARBaz', '1fooBar', '1FooBar', 'FOOBar');
foreach($tests as $test){ echo $test . " => " . split_camel_case($test) . "<br />"; }
function split_camel_case($root){
return implode(' ', preg_split('/(?<=[a-z])(?![a-z])/', $root, -1, PREG_SPLIT_NO_EMPTY));
}
我从中得到的是:
FooBar => Foo Bar
fooBar => foo Bar
Foobar => Foobar
FooBar1 => Foo Bar 1
FooBAR => Foo BAR
FooBARBaz => Foo BARBaz
1fooBar => 1foo Bar
1FooBar => 1Foo Bar
FOOBar => FOOBar
最后四个不正确,它们应该是:
FooBARBaz => Foo BAR Baz
1fooBar => 1 foo Bar
1FooBar => 1 Foo Bar
FOOBar => FOO Bar
我在另一个StackOverflow问题中找到了这个模式,但是我找不到任何完全符合我需要的东西。任何帮助将不胜感激。
答案 0 :(得分:2)
使用|
添加其他案例作为额外的可能性:
$tests = array('FooBar', 'fooBar', 'Foobar', 'FooBar1', 'FooBAR', 'FooBARBaz', '1fooBar', '1FooBar', 'FOOBar');
foreach($tests as $test){ echo $test . " => " . split_camel_case($test) . "<br />"; }
function split_camel_case($root){
return implode(' ', preg_split('/(?<=[a-z])(?![a-z])|(?<=[0-9])(?![0-9])|(?<=[A-Z])(?=[A-Z][a-z])/', $root, -1, PREG_SPLIT_NO_EMPTY));
}