note 102664 deleted from function.explode by googleguy
| From: | googleguy@php.net | Date: | Thu, 22 Nov 2012 16:54:47 +0000 |
| Subject: | note 102664 deleted from function.explode by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-192093@lists.php.net to get a copy of this message | ||
Note Submitter: Aram Kocharyan
----
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
)