Skip to content

Instantly share code, notes, and snippets.

@Caffe1neAdd1ct
Created August 30, 2018 10:34
Show Gist options
  • Save Caffe1neAdd1ct/9f70cf8bbe78fa95ce749cab4fdf3776 to your computer and use it in GitHub Desktop.
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.
<?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