Created
August 30, 2018 10:34
-
-
Save Caffe1neAdd1ct/9f70cf8bbe78fa95ce749cab4fdf3776 to your computer and use it in GitHub Desktop.
Splits a string into chunks preferring $min until the end chunk then prefer $max.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Splits $str into chunks preferring $min until the end chunk. | |
* If the remaining chars will fit in a max chunk then max is used. | |
* @param string $str | |
* @param integer $min | |
* @param integer $max | |
*/ | |
public function str_chunk_min_max($str, $min=1, $max=1) | |
{ | |
$strParts = str_split($str, $min); | |
if(strlen($str) <= $min) { | |
return $strParts; | |
} | |
$strPartsLastKey = count($strParts) - 1; | |
$lastPartSize = strlen(end($strParts)); | |
/** combine the last strPart to the penultimate strPart if able to fit in the max chunk size */ | |
if($strPartsLastKey > 1 && $lastPartSize < $max && $lastPartSize !== 0) { | |
$currentKey = $strPartsLastKey; | |
$maxStr = $strParts[$strPartsLastKey]; | |
/** remove last value as being appended */ | |
unset($strParts[$strPartsLastKey]); | |
while(strlen($maxStr) < $max) { | |
$currentKey--; | |
$partChars = str_split($strParts[$currentKey]); | |
while(count($partChars) > 0 && strlen($maxStr) < $max) { | |
$maxStr = array_pop($partChars) . $maxStr; | |
} | |
if(count($partChars) === 0) { | |
unset($strParts[$currentKey]); | |
} | |
} | |
$strParts[] = $maxStr; | |
} | |
return $strParts; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment