1

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?

2
  • 1
    what's inefficient about that? looks fine to me Commented Jan 26, 2012 at 0:00
  • The most efficient way is whichever is the most readable, without fail. Do not make your code an eye-sore for the sake of 0.04ms per request. Commented Jul 8, 2015 at 9:02

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks will try this, I tried using preg_replace before but couldn't get it right.
This worked great! Could you tell me what ' \\1' that bit means please or a link so I could find out?
It's a back reference. It tells regex to take the text that it found in the original string and "paste" it back here.
Thank you this is better than what I was using.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.