Quick Tip for Splitting Strings in PHP

Tuesday, 16 December 2008

Splitting strings into an array is generally pretty easy using something like explode but if your data is a little less consistent using the split function makes it a lot easier since you can break the string into parts using a regular expression.

For example:

$fruit = 'apples,oranges,bananas,grapes';
$fruit_array = explode(',', $fruit);

But if your string has commas with optional spaces afterward you’d need to do something like this:

$fruit2 = 'apples, oranges,bananas, grapes';
$fruit2_array = split(', *', $fruit2);

The regular expression is now splitting the string based on a comma and “zero or more” spaces. Now both of these will render the same array:

Array
(
    [0] => apples
    [1] => oranges
    [2] => bananas
    [3] => grapes
)

Questions or Comments about this entry?
Send me a message on Twitter (@mirthlab) or via Email.