note 102664 modified in function.explode by danbrown

[email protected] Mon, 28 Feb 2011 06:36:42 -0800
Newsgroups php.notes
Message-ID <[email protected]>
Here is a function to explode a comma separated string and trim the elements of any whitespace that may come before or after the comma, and 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
)

--was--
Here is a function to explode a comma separated string and trim the elements of any whitespace that may come before or after the comma.

<?php

function explode_trim($str) {
    $str = preg_replace('#[\\s]*,[\\s]*#', ',', $str);
    return explode(',', $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
)

http://php.net/manual/en/function.explode.php