Php regular expression replace?

I want to separate alpha-numeric (with a space) and non-alpha-numeric comma in a string.

I tried with this ...

$str = "This is !@ #$%^&"; preg_replace("/([a-z0-9_\s])([^a-z0-9_])/i", "$1, $2", $str); 

But I got this result ...

This, is ,! @ # $% ^ &

How can I fix the pattarn search file to get this result?

It:! @ # $% ^ &

Thanks.

+1
source share
2 answers

You should have canceled everything in the first group for the second, for example:

 preg_replace("/([a-z0-9_\s])([^a-z0-9_\s])/i", "$1, $2", $str); 

Otherwise, it will also be divided into spaces.

+3
source

You will probably have to do this in several iterations. Try the following:

 $preg = array( "/([\w\s]+)/i", "/([\W\s]+)/i" ): $replace = array( "\\1, ", "\\1 " ); $result = rtrim( preg_replace( $preg, $replace, $input ) ); // rtrim to get rid of any excess spaces 
0
source

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


All Articles