简体   繁体   中英

PHP regular expression replace?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM