navitronic
navitronic

Reputation: 563

Multiple regular expressions in PHP

Is there a better to handle running multiple regular expressions in PHP (or in general)?

I have the code below to replace non alphanumeric characters with dashes, once the replacement has happened I want to remove the instances of multiple dashes.

$slug = preg_replace('/[^A-Za-z0-9]/i', '-', $slug);
$slug = preg_replace('/\-{2,}/i', '-', $slug);

Is there a neater way to do this? ie, setup the regex pattern to replace one pattern and then the other?

(I'm like a kid with a fork in a socket when it comes to regex)

Upvotes: 3

Views: 863

Answers (3)

anubhava
anubhava

Reputation: 784938

If $slug already doesn't have multiple hyphens then you can avoid 2nd preg_replace call by using first preg_replace call like this:

$slug = preg_replace('/[^a-z0-9]+-?/i', '-', $slug);

Above code will find non-alphanumeric character optionally followed by hyphen and replace that matched text by a single hyphen -. hence no need to make 2nd preg_replace call.

Upvotes: 0

mu is too short
mu is too short

Reputation: 434595

You can eliminate the second preg_replace by saying what you really mean in the first one:

$slug = preg_replace('/[^a-z0-9]+/i', '-', $slug);

What you really mean is "replace all sequences of one or more non-alphanumeric characters with a single hyphen" and that's what /[^a-z0-9]+/i does. Also, you don't need to include the upper and lower case letters when you specify a case insensitive regex so I took that out.

Upvotes: 4

eykanal
eykanal

Reputation: 27017

No. What you have is the appropriate way to deal with this problem.

Consider it from this angle: regular expressions are meant to find a pattern (a single pattern) and deal with it somehow. As such, by trying to deal with more than one pattern at a time, you're only giving yourself headaches. It's best as is, for everyone involved.

Upvotes: 2

Related Questions