Convert multiple instances of a character to only one (aa = a) using preg_replace?

I have a string, I want to convert several expressions - only to one - .

I tried preg_replace('/--+/g', '-', $string) , but that just returns nothing ..

+6
source share
3 answers

You should not use g in the pattern, and you can simplify your regex:

 preg_replace('/-+/', '-', $string); 

Backslash screens are not required.

On http://ideone.com/IOlpv :

 <? $string = "asdfsdfd----sdfsdfs-sdf-sdf"; echo preg_replace('/-+/', '-', $string); ?> 

Conclusion:

 asdfsdfd-sdfsdfs-sdf-sdf 
+4
source
 preg_replace('/([\-]+)/', '-', $string) 
+3
source

Your code displays the following error:

Warning: preg_replace (): Unknown modifier 'g'

No modifier g . Try:

 preg_replace('/--+/', '-', $string) 
+1
source

Source: https://habr.com/ru/post/924844/


All Articles