Friday, May 4, 2012

Can regex do this faster?


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;
}


Source: Tips4all

3 comments:

  1. 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!

    ReplyDelete
  2. 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.

    ReplyDelete
  3. 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.

    ReplyDelete