我有一个方法,现在,将转换我的骆驼串蛇的情况下,但它的分解成preg_replace()
三个电话:使用的preg_replace()转换成首字母大写snake_case
public function camelToUnderscore($string, $us = "-")
{
// insert hyphen between any letter and the beginning of a numeric chain
$string = preg_replace('/([a-z]+)([0-9]+)/i', '$1'.$us.'$2', $string);
// insert hyphen between any lower-to-upper-case letter chain
$string = preg_replace('/([a-z]+)([A-Z]+)/', '$1'.$us.'$2', $string);
// insert hyphen between the end of a numeric chain and the beginning of an alpha chain
$string = preg_replace('/([0-9]+)([a-z]+)/i', '$1'.$us.'$2', $string);
// Lowercase
$string = strtolower($string);
return $string;
}
我写了测试,以验证其
$test_values = [
'foo' => 'foo',
'fooBar' => 'foo-bar',
'foo123' => 'foo-123',
'123Foo' => '123-foo',
'fooBar123' => 'foo-bar-123',
'foo123Bar' => 'foo-123-bar',
'123FooBar' => '123-foo-bar',
];
我不知道是否有减少我preg_replace()
调用单行,这将给我相同的结果的方式:精度,并将其与输入下面的数组(array('input' => 'output')
)正常工作。有任何想法吗?
注:Referring to this post,我的研究已经表明了我preg_replace()
是正则表达式让我几乎结果我想要的,只是它不就foo123
的工作,例如将其转换为foo-123
。
@AdrienLeber阅读我的问题的底线。它不是重复的。我阅读了这篇文章,并没有帮助我的问题。 – Matt
对不起,我删除了重复的标志,并根据您在问题中提及的帖子上共享的内容发布了新答案。 – JazZ
@pete注意 – Matt