Vlad
Vlad

Reputation: 475

Multiple regexp replacements in php

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

Answers (3)

Chriszuma
Chriszuma

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

nickb
nickb

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

Demo

Upvotes: 2

Julien
Julien

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

Related Questions