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;
}
Regex has an interpreted mode and a compiled mode. The compiled mode takes longer to start, but is generally faster.
Regular expressions are not always faster than a simple search. It all depends on context. It depends on the complexity of the expression, the length of the document being searched, and a whole host of factors. What happens is that the regular expression will be compiled into a simple parser (which takes time).
Yet matching a string with a regex can be surprisingly slow. So slow it can even stop any JS app or take 100% of a server CPU time causing denial of service (DOS). At TextMaster we used regular expressions in an important part of our translation platform.
String operations will always be faster than regular expression operations. Unless, of course, you write the string operations in an inefficient way. Regular expressions have to be parsed, and code generated to perform the operation using string operations.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With