Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can regex do this faster?

Tags:

regex

php

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;
}
like image 216
fire Avatar asked Feb 03 '10 17:02

fire


People also ask

Does compiling regex make it faster?

Regex has an interpreted mode and a compiled mode. The compiled mode takes longer to start, but is generally faster.

Is regex the fastest?

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).

Is regex fast or slow?

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.

Is there anything faster than regex?

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.


1 Answers

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!

like image 101
FrustratedWithFormsDesigner Avatar answered Oct 01 '22 02:10

FrustratedWithFormsDesigner