views:

74

answers:

2

I want to split alpha-numeric (with space) and non-alpha-numeric by 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 search pattarn to get this result?

This is, !@#$%^&

Thanks.

+2  A: 

You should have negated everything in the first group for the second, like so:

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

Otherwise, it'd split on spaces as well.

K Prime
That would work for his example text but, because the regex for splitting is static, it will probably not work for anything else
Kevin Peno
Sorry, but what do you mean? Can share some examples where it'd fail?
K Prime
A: 

You will probably have to do this in multiple iterations. Try this:

$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
Kevin Peno