note 102664 modified in function.explode by danbrown
| From: | danbrown@php.net | Date: | Mon, 28 Feb 2011 14:36:42 +0000 |
| Subject: | note 102664 modified in function.explode by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-177396@lists.php.net to get a copy of this message | ||
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