Tom Butler's programming blog

Split/explode a string in PHP with an escape character

Explode with escape

This seems like a simple task that should be supported natively in PHP. Unfortunately it's not. The problem is taking a string e.g.

a,b,c\,d,e,f

And splitting it on , while ignoring any commas that have been escaped using \. There are a few solutions online using RegEx, however that feels like overkill for such a simple task. Here's a simple piece of code that performs an escaped split without needing regular expressions:

$foo 'a,b,c\\,d,e';

function 
explodeEscaped($delimiter$str$escapeChar '\\') {
    
//Just some random placeholders that won't ever appear in the source $str
    
$double "\0\0\0_doub";
    
$escaped "\0\0\0_esc";
    
$str str_replace($escapeChar $escapeChar$double$str);
    
$str str_replace($escapeChar $delimiter$escaped$str);
    
    
$split explode($delimiter$str);
    foreach (
$split as &$val$val str_replace([$double$escaped], [$escapeChar$delimiter], $val);
    return 
$split;
}

print_r(explodeEscaped(','$foo'\\'));

Note: Because \ has special meaing in PHP it has to be escaped in the string when declaring $foo!

This prints:

Array ( [0] => [1] => [2] => c,[3] => )

To be consistet with other escape characters, it also supports double escaping in case you need an escape character in the original string for example:

a,b,c\,d,e\\,f

The second last element here should be "e\" because the \ is escaped and treated like a normal \

$foo 'a,b,c\\,d,e\\\\,f';
print_r(explodeEscaped(','$foo'\\'));

Note: Because \ has special meaing in PHP it has to be escaped in the string when declaring $foo so \\ becomes \\\\

Prints:

Array ( [0] => [1] => [2] => c,[3] => e\ [4] => )