需要一个复杂的正则表达式来拆分驼峰大小写和数字
Need a complex regular expression to split on camel case and numbers
我需要拆分大写字母和数字,将字符串中任意位置的一系列大写字母拆分为一个完整的单词。仅用示例进行解释可能是最简单的,请参见下面的测试脚本:
$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
我在另一个 Whosebug 问题中找到了该模式,但我没能找到任何完全符合我需要的模式。任何帮助将不胜感激。
只需使用 |
:
添加其他情况作为额外的可能性
$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));
}
我需要拆分大写字母和数字,将字符串中任意位置的一系列大写字母拆分为一个完整的单词。仅用示例进行解释可能是最简单的,请参见下面的测试脚本:
$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
我在另一个 Whosebug 问题中找到了该模式,但我没能找到任何完全符合我需要的模式。任何帮助将不胜感激。
只需使用 |
:
$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));
}