有没有一种简单的方法可以让php camelcase为我提供一个字符串?我使用的是Laravel框架,我想在搜索功能中使用一些简写。
它看起来像下面这样。。。
private function search(Array $for, Model $in){
$results = [];
foreach($for as $column => $value){
$results[] = $in->{$this->camelCase($column)}($value)->get();
}
return $results;
}
像一样调用
$this->search(['where-created_at' => '2015-25-12'], new Ticket);
因此,我将使用的搜索函数中的结果调用是
$in->whereCreateAt('2015-25-12')->get();
唯一我搞不清楚的是骆驼套。。。
您是否考虑过使用Laravel内置的驼色大小写函数?
$camel = camel_case('foo_bar');
完整的详细信息可以在这里找到:
https://laravel.com/docs/4.2/helpers#strings
因此,可以使用的一种可能的解决方案如下。
private function camelCase($string, $dontStrip = []){
/*
* This will take any dash or underscore turn it into a space, run ucwords against
* it so it capitalizes the first letter in all words separated by a space then it
* turns and deletes all spaces.
*/
return lcfirst(str_replace(' ', '', ucwords(preg_replace('/[^a-z0-9'.implode('',$dontStrip).']+/', ' ',$string))));
}
这是一行代码,由一个函数包装,其中有很多内容…
故障
dontStrip
变量是什么
简单地说,它是一个数组,应该包含任何你不想从camelCasing中删除的东西。
你在用那个变量做什么
我们将数组中的每个元素都放入一个字符串中。
把它想象成这样:
function implode($glue, $array) {
// This is a native PHP function, I just wanted to demonstrate how it might work.
$string = '';
foreach($array as $element){
$string .= $glue . $element;
}
return $string;
}
通过这种方式,您基本上将数组中的所有元素粘合在一起。
preg_replace是什么,它在做什么
preg_replace
是一个函数,它使用正则表达式(也称为正则表达式)来搜索并替换它找到的与所需正则表达式匹配的任何值。。。
正则表达式搜索的说明
上面搜索中使用的正则表达式将数组$dontStrip
内爆为一个小比特a-z0-9
,这意味着任何字母a到Z以及数字0到9。小^
位告诉regex,它正在寻找任何不在它后面的东西。因此,在这种情况下,它正在查找不在数组或字母或数字中的任何和所有东西。
如果你是regex的新手,并且你想摆弄它,那么regex101是一个很好的地方
ucwords
这可以很容易地作为大写单词。它将使用任何单词(一个单词是由空格分隔的任何一位字符),并将第一个字母大写。
echo ucwords('hello, world!');
将打印"你好,世界!"
好吧,我明白什么是preg_replace,什么是str_replace
str_replace
是preg_replace
的一个较小、功能较弱但仍然非常有用的弟弟/妹妹。我的意思是,它也有类似的用途。str_replace
没有正则表达式,但使用了一个文本字符串,所以无论您在第一个参数中键入什么,它都会查找到。
旁注,值得一提的是,对于那些考虑只使用preg_replace的人来说,str_replace也同样有效。在大型应用程序上,str_replace的基准测试速度要比preg_replace快一些
lcfirst
什么
从PHP 5.3开始,我们就可以使用lcfirst
函数,它与ucwords非常相似,只是一个文本操作函数`lcfirst将第一个字母转换为小写形式。
echo lcfirst('HELLO, WORLD!');
将打印"你好,世界!"
结果
记住所有这些,camelBase函数使用不同的非字母数字字符作为断点,将字符串转换为camelBase字符串。
有一个通用的开源库,其中包含一个方法,用于对几种流行的案例格式执行案例转换。这个库被称为TurboCommons,StringUtils中的formatCase()方法进行大小写转换。
https://github.com/edertone/TurboCommons
要使用它,请将phar文件导入您的项目并:
use org'turbocommons'src'main'php'utils'StringUtils;
echo StringUtils::formatCase('sNake_Case', StringUtils::FORMAT_CAMEL_CASE);
// will output 'sNakeCase'
您可以使用Laravel内置的camel-case辅助函数
use Illuminate'Support'Str;
$converted = Str::camel('foo_bar');
// fooBar
完整的详细信息可以在这里找到:
https://laravel.com/docs/9.x/helpers#method-驼色案例
使用内置的Laravel Helper函数-camel_case()
$camelCase = camel_case('your_text_here');