开发者

Multiple regular expressions in PHP

开发者 https://www.devze.com 2023-03-08 02:57 出处:网络
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

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('开发者_如何学C/[^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_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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消