note 102892 deleted from function.str-split by danbrown
| From: | danbrown@php.net | Date: | Sun, 13 Mar 2011 03:29:38 +0000 |
| Subject: | note 102892 deleted from function.str-split by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-177831@lists.php.net to get a copy of this message | ||
Note Submitter: jaimthorn at yahoo dot com
----
A small function that splits a string into variable-length segments. Easier than substr-ing a
string to bits. :-)
/**
* Splits a string, based on the integer offsets supplied as variable argument list.
*
* @param string
* @param VARARG ints
* @return array
*/
function splitByOffsets( $string )
{
$retval = array();
$args = func_get_args();
array_shift( $args ); // Shift $string out.
$start = 0;
foreach( $args as $arg ) {
$retval[] = substr( $string, $start, $arg );
$start += $arg;
}
if( strlen( $string ) > $start ) {
$retval[] = substr( $string, $start );
}
return $retval;
}
// Split the string in chunks of 4, 2, and 2 characters, plus whatever is left.
$date = splitByOffsets( "20110313 is today's date", 4, 2, 2 );
echo 'Today is: ', $date[ 2 ], '-', $date[ 1 ], '-', $date[ 0 ]; //
Today is: 13-03-2011
echo 'Left is: ', $date[ 3 ]; // Left is: is
today's date