Search code examples
phpregexpreg-replacealphanumericnon-alphanumeric

Inject a comma between alphanumeric substrings and non-alphanumeric substrings


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

I tried with this:

$str = "This is !@#$%^&";
echo 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 pattern to get this result?

This is, !@#$%^&

Solution

  • 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.