PHP中某些字符串操作的最有效方法


Most efficient way of certain string manipulation in PHP?

我有一些字符串需要转换,比如

'hello world' = 'helloWorld'

反过来也是一样,

'helloWorld' = 'hello world'

到目前为止,我对这两种转换都只做了第一次,

$str = 'hello world';
$str = lcfirst(str_replace(' ', '', ucwords($str))); // helloWorld

第二,

$str = 'helloWorld';
$str = preg_split('/(?=[A-Z])/', $str);
$str = strtolower(implode(' ', $str)); // hello world

这难道不能更容易或更有效地实现吗?

您的camalize代码已经很好了。第二,你可以放弃分裂并内爆:

$str = 'helloWorld';
$str = strtolower(preg_replace('/(?<=''w)([A-Z])/', ' ''1', $str));
echo $str;
// output: hello world