使用preg_replace()将字母数字字符串从camelCase转换为snake_case


Using preg_replace() to convert alphanumeric strings from camelCase to snake_case

我现在有一个方法,将我的骆驼大小写字符串转换为蛇形大小写,但它分为三个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;
}

我编写了测试来验证它的准确性,并且它可以正确地使用以下输入数组(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',
];

我想知道是否有一种方法可以减少我的preg_replace()呼叫到单行,这将给我相同的结果。什么好主意吗?

注意:参考这篇文章,我的研究已经向我展示了一个preg_replace()正则表达式,它让我几乎我想要的结果,除了它不工作在foo123的例子将其转换为foo-123

您可以使用遍历在单个正则表达式中完成所有这些:

function camelToUnderscore($string, $us = "-") {
    return strtolower(preg_replace(
        '/(?<='d)(?=[A-Za-z])|(?<=[A-Za-z])(?='d)|(?<=[a-z])(?=[A-Z])/', $us, $string));
}

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

根据我之前标记的重复帖子,这是我的两点意见。这里公认的解决方案非常棒。我只是想尝试用共享的东西来解决这个问题:

function camelToUnderscore($string, $us = "-") {
    return strtolower(preg_replace('/(?<!^)[A-Z]+|(?<!^|'d)['d]+/', $us.'$0', $string));
}

示例:

Array
(
    [0] => foo
    [1] => fooBar
    [2] => foo123
    [3] => 123Foo
    [4] => fooBar123
    [5] => foo123Bar
    [6] => 123FooBar
)
foreach ($arr as $item) {
    echo camelToUnderscore($item);
    echo "'r'n";
}

输出:

foo
foo-bar
foo-123
123-foo
foo-bar-123
foo-123-bar
123-foo-bar

说明:

(?<!^)[A-Z]+      // Match one or more Capital letter not at start of the string
|                 // OR
(?<!^|'d)['d]+    // Match one or more digit not at start of the string
$us.'$0'          // Substitute the matching pattern(s)
在线正则表达式

这个问题已经解决了,所以我不会说我希望它有帮助,但也许有人会发现这有用。


编辑

这个正则表达式有限制:

foo123bar => foo-123bar
fooBARFoo => foo-barfoo

感谢@urban指出这一点。以下是他给出的三个解决方案的测试链接:

三个解决方案演示

来自同事:

$string = preg_replace(array($pattern1, $pattern2), $us.'$1', $string);可能会起作用

我的解决方案:

public function camelToUnderscore($string, $us = "-")
{
    $patterns = [
        '/([a-z]+)([0-9]+)/i',
        '/([a-z]+)([A-Z]+)/',
        '/([0-9]+)([a-z]+)/i'
    ];
    $string = preg_replace($patterns, '$1'.$us.'$2', $string);
    // Lowercase
    $string = strtolower($string);
    return $string;
}

您不需要忍受大量遍历或多组模式的低效率来定位单词或连续数字之间的位置。

使用贪婪匹配来查找所需的序列,然后用'K重置fullstring匹配,然后检查位置是否为字符串的末尾。所有符合条件的内容都应该接收分隔字符。这种贪婪模式的速度在于它消耗一个或多个序列并且从不回头。

我将从我的回答中省略strtolower()调用,因为它仅仅是挑战的噪音。

代码(演示):

preg_replace(
    '/(?:'d++|[A-Za-z]?[a-z]++)'K(?!$)/',
    '-',
    $tests
)

字/数之间的处理:

<表类>用户 步骤模式替换tbody> <<tr> Anubhava td> 660 /(?<='d)(?=[A-Za-z])|(?<=[A-Za-z])(?='d)|(?<=[a-z])(?=[A-Z]) '-' mickmackusa td> 337 /(?:'d++|[A-Za-z]?[a-z]++)'K(?!$)/ '-' tbody>