Reputation: 475
I need to perform a number of replacements on a string: remove non-alphanumeric characters, remove duplicate spaces, and capitalize first characters of individual words. Is it a good practice to create a single regexp expression for all 3 tasks, or will performance take a hit if I split this up in 3 separate preg_replace commands?
Upvotes: 1
Views: 134
Reputation: 4557
Generally, making your code more maintainable but slightly less efficient is preferable. Here you have the choice between one monstrous regex that will be painful to debug, or 3 very simple regexes, and I would choose the latter every time. You probably won't even notice a performance difference unless you're parsing millions of strings.
If you would like some good reading, this drive to make things as efficient as possible before they are working properly is known as Premature Optimization.
Upvotes: 3
Reputation: 59699
Use two regexes for the first two and then use ucwords. The first two operations aren't suited to be combined and they are fundamentally different (one replaces with nothing, one replaces with a single character of the match). Then, use ucwords
to avoid using another regex.
$result = preg_replace('/[^a-z\s]/i', '', $subject);
$result = preg_replace('/(\s)\s+/i', '$1', $result);
$result = ucwords( $result);
Upvotes: 2
Reputation: 282
generally less operations is better, but i think you'd need to be dealing with millions of strings before it made any noticeable difference
Upvotes: 0