I want to convert user input string
“something … un// important ,,, like-this”
to
“something-un-important-like-this”
So basically remove all recurring special characters with “-“. I’ve googled and came to this
preg_replace('/[-]+/', '-', preg_replace('/[^a-zA-Z0-9_-]/s', '-', strtolower($string)));
I’m curious as to know if this can be done with a single preg_replace().
Just to clear things out:
replace all special characters and blank space with a hyphen(-). If more occurrence appear consecutively replace them with single hyphen
My solution works perfectly as I want to but I’m looking to do the same in a single call
There was a similar question yesterday, but I don’t have it at hand.
In your current first pattern:
you’re looking for a single character only. If you make that a greedy match for one or more, the regular expression engine will automatically replace multiple of these with a single one:
You then still have the problem that existing
-inside the string are not caught, so you need to take them out of the “not-in” character class:This then should do it:
And as it’s only lowercase, you do not need to look for
A-Zas well, just another reduction:See as well Repetition and/or Quantifiers of which the
+is one of (see RepetitionDocs; Repetition with Star and Plusregular-expressions.info).Also if you take a look at the modifiersDocs, you’ll see that the s (PCRE_DOTALL) modifier is not necessary:
Hope this helps and explains you a little about the regular expression you’re using and also where you can find further documentation which is always helpful.