I'm trying to remove all leading, trailing and standalone hyphens from string:
-on-line - auction- website
Desired result:
on-line auction website
I came up with a working solution:
^-|(?<=\s)-|-(?=\s)|-$
But it looks to me a little bit amateur (isn't it?). So do you have a better solution?
You can use this pattern:
(?<!\S)-|-(?!\S)
example:
echo preg_replace('~(?<!\S)-|-(?!\S)~', '', '-on-line - auction- website');
Another possible pattern that uses a conditional statement: -(?(?!\S)|(?<!\S.))
This last one is interesting since it benefits of a single branch with a leading literal character. This way, the regex engine is able to quickly tests only positions in the string where the character appears (due to internal optimisations before the "normal" regex engine walk).
Note that the conditional statement isn't mandatory and can also be replaced with a non-capturing group adding a :
(it doesn't change the result but it's longer):
-(?:(?!\S)|(?<!\S.))
I guess it can be shortened to:
$repl = preg_replace('/(^|\s)-|-(\s|$)/', '$1$2', $str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With