tags:

views:

71

answers:

2

Does somebody know a quick and easy explode() like function that can ignore splitter characters that are enclosed in a pair of arbitrary characters (e.g. quotes)?

Example:

my_explode(
  "/", 
  "This is/a string/that should be/exploded.//But 'not/here',/and 'not/here'"
);

should result in an array with the following members:

This is
a string 
that should be 
exploded.

But 'not/here', 
and 'not/here'

the fact that the characters are wrapped in single quotes would spare them from being splitters.

Bonus points for a solution that can deal with two wrapper characters

(not/here)

A native PHP solution would be preferred, but I don't think such a thing exists!

+1  A: 

str_getcsv($str, '/')

There's a recipe for <5.3 on the linked page.

Ignacio Vazquez-Abrams
+1, was just about to post the same thing.
Andy E
doesnt work for me. doesnt recognize the `'` as enclosure.
Gordon
So then pass a different character as an enclosure.
Ignacio Vazquez-Abrams
doesnt matter. It returns `Array( [0] => This is [1] => a string [2] => that should be [3] => exploded. [4] => [5] => But 'not [6] => here', [7] => and 'not [8] => here')`
Gordon
Smells like a PHP bug to me then.
Ignacio Vazquez-Abrams
A: 

Something very near with preg_split : http://fr2.php.net/manual/en/function.preg-split.php#92632

It handles multiple wrapper characters AND multiple delimiter characters.

greg0ire
Cheers @greg0ire, this looks good but still needs a little work. I'll try changing it to my needs with my feeble knowledge of Regexes.
Pekka