note 98428 deleted from function.str-split by crell

From: Date: Wed, 29 Jun 2022 18:30:07 +0000
Subject: note 98428 deleted from function.str-split by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218686@lists.php.net to get a copy of this message
Note Submitter: anon ---- I needed a function that could split a string from the end with any left over chunk being at the beginning of the array (the beginning of the string). <?php function str_rsplit($str, $sz) { // splits a string "starting" at the end, so any left over (small chunk) is at the beginning of the array. if ( !$sz ) { return false; } if ( $sz > 0 ) { return str_split($str,$sz); } // normal split $l = strlen($str); $sz = min(-$sz,$l); $mod = $l % $sz; if ( !$mod ) { return str_split($str,$sz); } // even/max-length split // split return array_merge(array(substr($str,0,$mod)), str_split(substr($str,$mod),$sz)); } $str = 'aAbBcCdDeEfFg'; str_split($str,5); // return: {'aAbBc','CdDeE','fFg'} str_rsplit($str,5); // return: {'aAbBc','CdDeE','fFg'} str_rsplit($str,-5); // return: {'aAb','BcCdD','eEfFg'} ?>

« previous php.notes (#218686) next »