Several regexes in PHP

Is it possible to handle multiple regular expressions in PHP (or in general)?

I have the code below to replace non-alphanumeric characters with hyphens as soon as the replacement occurs. I want to delete instances of multiple dashes.

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

Is there an easier way to do this? those. install a regex pattern to replace one pattern and then another?

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

+3
source share
3 answers

You can eliminate the second preg_replaceby specifying what you really mean in the first:

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

, , " -- " /[^a-z0-9]+/i. , , .

+4

. .

: ( ) - . , , . , .

+2

$slug , preg_replace, preg_replace, :

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

Above the code, it will not find an alphanumeric character , but optionally a hyphen and replace this consistent text with one hyphen -. therefore no need to make a second call to preg_replace.

0
source

All Articles