我有一個方法,現在,將轉換我的駱駝串蛇的情況下,但它的分解成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