How to explode() Only Once in PHP?

You can specify the third argument to explode() to ensure that you only split the string once at the first match. To learn more about this, first familiarize yourself with the complete syntax of the explode() function:

// PHP 4+
explode($separator, $str, $limit);

When a positive value is supplied as the $limit, the returned array will contain a maximum of $limit elements, and the last element will contain the rest of the string. Therefore, if you set the limit to 2, then the returned array will contain ONE "exploded" element along with the last element containing the rest of the string. For example:

$str = 'foo|bar|baz|qux';
$separator = '|';
$result = explode($separator, $str, 2);

echo print_r($result, true); // output: ['foo', 'bar|baz|qux']

In case there's no match found for the $separator, the resulting array will contain only one element (i.e. the entire string itself):

$str = 'foo|bar|baz|qux';
$separator = '*';
$result = explode($separator, $str, 2);

echo print_r($result, true); // ['foo|bar|baz|qux']

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.