tags:

views:

240

answers:

3

I want to capitalise each word and combine it into 1 word, e.g:

home = Home
about-us = AboutUs

Here is the function I use at the moment, can regex do this better or more efficient?

public function formatClassName($name)
{
 $name = str_replace('-', ' ', $name);
 $name = ucwords($name);
 $name = str_replace(' ', '', $name);
 return $name;
}
+27  A: 

I don't think a regex can capitalize the words, so you'd still have to have two separate regexes, and I think with such simple cases, regular expressions are overkill (think hunting squirrels with artillery). This code is simple, clear and easy to understand. DON'T TOUCH IT!

FrustratedWithFormsDesigner
RegEx can capitalize the first letter, but your advice is dead on, KISS.
TravisO
Obviously, you've never hunted squirrels with artillery ;)
Hooray Im Helping
You can capitalize word with `preg` since you can pass the `/e` flag and put PHP code as the "replacement".
KennyTM
+12  A: 

With regex, you'd probably have to use something "complex", like preg_replace_callback (to be able to apply the strtoupper or ucwords function), which would make your code at least harder to understand -- and possibly slower, but the most important thing is that your code is easy to understand.

Considering your solution just works and is simple and easy, I would probably keep it, if I were in your place.

Pascal MARTIN
+4  A: 

This code works:

$in = Array("home", "about-us");
foreach ($in as $a) {

  ## this is the line you're looking for
  $out = preg_replace('/-?\b(.)/e', "strtoupper('$1')", $a);

  echo "$a  = $out<br/>";
}

But I doubt it's faster, and I agree with the other commenters that it's not necessarily better. Decreasing three lines to one hairy regexp is only good if you're golfing.

Nathan