note 102673 deleted from function.explode by danbrown

[email protected] Mon, 28 Feb 2011 06:36:48 -0800
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: Aram Kocharyan 

----

An improvement to my previous post, this version will also trim whitespace from the front and end of the string, as well as allow you to specify a delimiter yourself.

<?php

/* Performs explode() on a string with the given delimiter and trims all whitespace for the elements */
function explode_trim($str, $delimiter = ',') {
    if ( is_string($delimiter) ) {
        $str = trim(preg_replace('|\\s*(?:' . preg_quote($delimiter) . ')\\s*|', $delimiter, $str));
        return explode($delimiter, $str);
    }
    return $str;
}

// Test
$str = '    mouse ,cat , dog  ,  human    ';
$array = explode_trim($str);
print_r($array);

?>

This will output:
(
    [0] => mouse
    [1] => cat
    [2] => dog
    [3] => human
)