如何将PascalCase转换为snake_case?
如果我有:
$string = "PascalCase";
我需要
"pascal_case"
PHP 是否提供了用于此目的的函数?
If I had:
$string = "PascalCase";
I need
"pascal_case"
Does PHP offer a function for this purpose?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
更短的解决方案:与编辑器类似,具有简化的正则表达式并修复“尾随下划线”问题:
PHP 演示< /a> |
正则表达式演示
请注意,像
SimpleXML
这样的情况将转换为simple_x_m_l
使用上述解决方案。这也可以被认为是驼峰式大小写表示法的错误使用(正确的是SimpleXml
),而不是算法的错误,因为这种情况总是不明确的 - 即使将大写字符分组为一个字符串(>simple_xml
)这样的算法在其他边缘情况下总是会失败,例如XMLHTMLConverter
或缩写附近的单字母单词等。如果您不介意(相当罕见的)边缘情况并且想要正确处理SimpleXML
,您可以使用稍微复杂一点的解决方案:PHP Demo |
正则表达式演示
A shorter solution: Similar to the editor's one with a simplified regular expression and fixing the "trailing-underscore" problem:
PHP Demo |
Regex Demo
Note that cases like
SimpleXML
will be converted tosimple_x_m_l
using the above solution. That can also be considered a wrong usage of camel case notation (correct would beSimpleXml
) rather than a bug of the algorithm since such cases are always ambiguous - even by grouping uppercase characters to one string (simple_xml
) such algorithm will always fail in other edge cases likeXMLHTMLConverter
or one-letter words near abbreviations, etc. If you don't mind about the (rather rare) edge cases and want to handleSimpleXML
correctly, you can use a little more complex solution:PHP Demo |
Regex Demo
尝试一下大小:
输出:
这实现了以下规则:
Try this on for size:
Output:
This implements the following rules:
一个简洁的解决方案,可以处理一些棘手的用例:
可以处理所有这些情况:
您可以在此处测试此功能:http:// /syframework.alwaysdata.net/decamelize
A concise solution and can handle some tricky use cases:
Can handle all these cases:
You can test this function here: http://syframework.alwaysdata.net/decamelize
Symfony Serializer 组件 有一个 CamelCaseToSnakeCaseNameConverter 具有两个方法
normalize()
和denormalize()
。这些可以按如下方式使用:The Symfony Serializer Component has a CamelCaseToSnakeCaseNameConverter that has two methods
normalize()
anddenormalize()
. These can be used as follows:从 Ruby 的
String#camelize
和String#decamelize
移植。上述解决方案可能忽略的一个技巧是“e”修饰符,它会导致
preg_replace
将替换字符串评估为 PHP 代码。Ported from Ruby's
String#camelize
andString#decamelize
.One trick the above solutions may have missed is the 'e' modifier which causes
preg_replace
to evaluate the replacement string as PHP code.这里的大多数解决方案都让人感觉很严厉。这是我使用的:
“CamelCASE”转换为“camel_case”
lcfirst($camelCase)
将降低第一个字符(避免“CamelCASE”转换后的输出以下划线开头)[AZ]
找到大写字母+
会将每个连续的大写字母视为一个单词(避免将“CamelCASE”转换为camel_C_A_S_E)ThoseSPECCases
-> ;those_spec_cases
而不是those_speccases
strtolower([…])
将输出转换为小写Most solutions here feel heavy handed. Here's what I use:
"CamelCASE" is converted to "camel_case"
lcfirst($camelCase)
will lower the first character (avoids 'CamelCASE' converted output to start with an underscore)[A-Z]
finds capital letters+
will treat every consecutive uppercase as a word (avoids 'CamelCASE' to be converted to camel_C_A_S_E)ThoseSPECCases
->those_spec_cases
instead ofthose_speccases
strtolower([…])
turns the output to lowercasesphp 没有为此提供内置函数,但这是我使用的
拆分器可以在函数调用中指定,因此您可以像这样调用它
php does not offer a built in function for this afaik, but here is what I use
the splitter can be specified in the function call, so you can call it like so
我遇到了类似的问题,但找不到任何满足如何将 CamelCase 转换为 Snake_case 的答案,同时避免使用带有下划线的名称或全部大写缩写的重复或冗余下划线
_
。问题如下:
我写的解决方案是一个简单的两个函数调用,小写和搜索并替换连续的小写-大写字母:
I had a similar problem but couldn't find any answer that satisfies how to convert CamelCase to snake_case, while avoiding duplicate or redundant underscores
_
for names with underscores, or all caps abbreviations.Th problem is as follows:
The solution I wrote is a simple two functions call, lowercase and search and replace for consecutive lowercase-uppercase letters:
“CamelCase”到“camel_case”:
或:
"CamelCase" to "camel_case":
or:
如果您正在寻找 PHP 5.4 版本和更高版本,这里的答案是代码:
If you are looking for a PHP 5.4 version and later answer here is the code:
您需要通过它运行一个正则表达式来匹配每个大写字母(除非它位于开头),并将其替换为下划线加该字母。 utf-8 解决方案是这样的:
如果您不确定字符串的大小写,最好先检查一下,因为此代码假定输入是
camelCase
而不是underscore_Case
> 或dash-Case
,因此如果后者有大写字母,则会为其添加下划线。cletus 接受的答案过于复杂,恕我直言,它仅适用于拉丁字符。我发现这是一个非常糟糕的解决方案,并且想知道为什么它会被接受。将
TEST123String
转换为test123_string
不一定是有效的要求。我宁愿保持简单并将ABCccc
分离为a_b_cccc
而不是ab_cccc
因为这样不会丢失信息,并且向后转换将给出准确的信息我们开始使用的字符串相同。即使您想以其他方式执行此操作,也可以相对轻松地使用正向lookbehind(? 或两个没有后向的正则表达式(如果您不是正则表达式专家)。无需将其拆分为子字符串,更不用说在
strtolower
和lcfirst
之间做出选择,其中仅使用strtolower
就完全没问题了。You need to run a regex through it that matches every uppercase letter except if it is in the beginning and replace it with underscrore plus that letter. An utf-8 solution is this:
If you are not sure what case your string is, better to check it first, because this code assumes that the input is
camelCase
instead ofunderscore_Case
ordash-Case
, so if the latters have uppercase letters, it will add underscores to them.The accepted answer from cletus is way too overcomplicated imho and it works only with latin characters. I find it a really bad solution and wonder why it was accepted at all. Converting
TEST123String
intotest123_string
is not necessarily a valid requirement. I rather kept it simple and separatedABCccc
intoa_b_cccc
instead ofab_cccc
because it does not lose information this way and the backward conversion will give the exact same string we started with. Even if you want to do it the other way it is relative easy to write a regex for it with positive lookbehind(?<!^)\p{Lu}\p{Ll}|(?<=\p{Ll})\p{Lu}
or two regexes without lookbehind if you are not a regex expert. There is no need to split it up into substrings not to mention deciding betweenstrtolower
andlcfirst
where using juststrtolower
would be completely fine.简短的解决方案:
Short solution:
一点也不花哨,但是简单而快速:
Not fancy at all but simple and speedy as hell:
使用 Symfony 字符串
Use Symfony String
不使用正则表达式的版本可以在 Alchitect 源中找到:
A version that doesn't use regex can be found in the Alchitect source:
所以这里有一句话:
So here is a one-liner:
danielstjules/Stringy 提供了一种将字符串从驼峰命名法转换为蛇形命名法的方法。
danielstjules/Stringy provieds a method to convert string from camelcase to snakecase.
Laravel 5.6 提供了一种非常简单的方法来执行此操作:
它的作用:如果它发现给定字符串中至少有一个大写字母,它会使用 正向前视 搜索任何字符 (
.
) 后跟大写字母 ((?=[AZ])< /代码>)。然后,它将找到的字符替换为其值,后跟分隔符
_
。Laravel 5.6 provides a very simple way of doing this:
What it does: if it sees that there is at least one capital letter in the given string, it uses a positive lookahead to search for any character (
.
) followed by a capital letter ((?=[A-Z])
). It then replaces the found character with it's value followed by the separactor_
.从 Rails 直接移植(减去对 :: 或首字母缩略词的特殊处理)将是
Knowing PHP,这将比此处给出的其他答案中发生的手动解析更快。缺点是您无法选择使用什么作为单词之间的分隔符,但这不是问题的一部分。
另请检查相关rails源代码
请注意,这适用于 ASCII 标识符。如果您需要对 ASCII 范围之外的字符执行此操作,请使用
preg_match
的“/u”修饰符并使用mb_strtolower
。The direct port from rails (minus their special handling for :: or acronyms) would be
Knowing PHP, this will be faster than the manual parsing that's happening in other answers given here. The disadvantage is that you don't get to chose what to use as a separator between words, but that wasn't part of the question.
Also check the relevant rails source code
Note that this is intended for use with ASCII identifiers. If you need to do this with characters outside of the ASCII range, use the '/u' modifier for
preg_match
and usemb_strtolower
.这是我对一个六年前问题的贡献,天知道有多少答案......
它将把提供的字符串中驼峰式的所有单词转换为蛇形式。例如,“SuperSpecialAwesome 和 FizBuzz καιKάτιAκόμα”将转换为“super_special_awesome 和 fizz_buzz και_κάτι_ακόμα”。
Here is my contribution to a six-year-old question with god knows how many answers...
It will convert all words in the provided string that are in camelcase to snakecase. For example "SuperSpecialAwesome and also FizBuzz καιΚάτιΑκόμα" will be converted to "super_special_awesome and also fizz_buzz και_κάτι_ακόμα".
Yii2 有不同的函数来将单词“snake_case”从“CamelCase”变为“snake_case”。
Yii2 have the different function to make the word snake_case from CamelCase.
这是较短的方法之一:
This is one of shorter ways:
如果您没有使用 Composer for PHP,那么您就是在浪费时间。
https://github.com/doctrine/inflector/blob/master/docs/en/index.rst
If you are not using Composer for PHP you are wasting your time.
https://github.com/doctrine/inflector/blob/master/docs/en/index.rst
这里最糟糕的答案非常接近最好的答案(使用框架)。不,不要,只需查看源代码即可。看看一个完善的框架使用什么将是一个更可靠的方法(经过尝试和测试)。 Zend 框架有一些适合您需求的单词过滤器。 来源。
这是我从源代码中改编的几种方法。
The worst answer on here was so close to being the best(use a framework). NO DON'T, just take a look at the source code. seeing what a well established framework uses would be a far more reliable approach(tried and tested). The Zend framework has some word filters which fit your needs. Source.
here is a couple of methods I adapted from the source.
有一个库提供此功能:
There is a library providing this functionality:
如果您使用 Laravel 框架,则可以仅使用 snake_case() 方法。
If you use Laravel framework, you can use just snake_case() method.
如何在不使用正则表达式的情况下去骆驼化:
编辑:
在 2019 年我将如何做到这一点:
PHP 7.3 及之前:
以及 PHP 7.4+:
How to de-camelize without using regex:
An edit:
How would I do that in 2019:
PHP 7.3 and before:
And with PHP 7.4+:
如果您使用 Laravel 框架,则存在更简单的内置方法:
请参阅此处的文档:
https://laravel.com/docs/9.x/helpers#方法蛇形案例
If you're using the Laravel framework, a simpler built-in method exists:
See documentation here:
https://laravel.com/docs/9.x/helpers#method-snake-case
开源 TurboCommons 库在 StringUtils 类中包含一个通用的 formatCase() 方法,它允许您将字符串转换为许多常见的大小写格式,例如 CamelCase、UpperCamelCase、LowerCamelCase、snake_case、Title Case 等。
https://github.com/edertone/TurboCommons
要使用它,请将 phar 文件导入到您的项目中和:
The open source TurboCommons library contains a general purpose formatCase() method inside the StringUtils class, which lets you convert a string to lots of common case formats, like CamelCase, UpperCamelCase, LowerCamelCase, snake_case, Title Case, and many more.
https://github.com/edertone/TurboCommons
To use it, import the phar file to your project and: