novactown.com
novactown.com

Reputation: 125

Most efficient way of certain string manipulation in PHP?

I have strings that need converting like so,

'hello world' = 'helloWorld'

And also the same in reverse,

'helloWorld' = 'hello world'

So far all I have for both the conversions is this for the first,

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

And the second,

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

Can this not be achieved any easier or any more efficient?

Upvotes: 1

Views: 114

Answers (1)

webbiedave
webbiedave

Reputation: 48897

Your camelize code is already good. For the second, you could forgo the split and implode:

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

Upvotes: 1

Related Questions