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)
You can eliminate the second
preg_replaceby saying what you really mean in the first one: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]+/idoes. 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.