Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regexp - remove all leading, trailing and standalone hyphens

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?

like image 949
Koralek M. Avatar asked Dec 11 '22 09:12

Koralek M.


2 Answers

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.))
like image 50
Casimir et Hippolyte Avatar answered Dec 28 '22 07:12

Casimir et Hippolyte


I guess it can be shortened to:

$repl = preg_replace('/(^|\s)-|-(\s|$)/', '$1$2', $str);
like image 38
anubhava Avatar answered Dec 28 '22 07:12

anubhava