Mat*_*att 10 php regex preg-replace
我现在有一个方法将我的驼峰案例字符串转换为蛇案例,但它分为三个调用preg_replace()
:
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;
}
Run Code Online (Sandbox Code Playgroud)
我编写了测试来验证其准确性,并且它可以正常使用以下输入数组(array('input' => 'output')
):
$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',
];
Run Code Online (Sandbox Code Playgroud)
我想知道是否有办法减少我preg_replace()
对单行的调用,这会给我相同的结果.有任何想法吗?
注意:参考这篇文章,我的研究向我展示了一个preg_replace()
正则表达式,它几乎得到了我想要的结果,除了它不能foo123
用于将其转换为的示例foo-123
.
anu*_*ava 16
你可以使用lookarounds在一个正则表达式中完成所有这些:
function camelToUnderscore($string, $us = "-") {
return strtolower(preg_replace(
'/(?<=\d)(?=[A-Za-z])|(?<=[A-Za-z])(?=\d)|(?<=[a-z])(?=[A-Z])/', $us, $string));
}
Run Code Online (Sandbox Code Playgroud)
RegEx说明:
(?<=\d)(?=[A-Za-z]) # if previous position has a digit and next has a letter
| # OR
(?<=[A-Za-z])(?=\d) # if previous position has a letter and next has a digit
| # OR
(?<=[a-z])(?=[A-Z]) # if previous position has a lowercase and next has a uppercase letter
Run Code Online (Sandbox Code Playgroud)