Created
March 19, 2020 21:46
-
-
Save tylerwiegand/2c632bae37de36b4f9578136cb65c254 to your computer and use it in GitHub Desktop.
stringHalver
This file contains 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 | |
// When you want to split strings by spaces without rounding up | |
function string_parts($string, $parts = 2) | |
{ | |
$array = preg_split('/\s+/', $string); | |
if (! (count($array) > 1)) { | |
return $string; | |
} | |
$chunks = array_chunk($array, floor(count($array) / $parts)); | |
if (count($chunks) > $parts) { | |
$popped = array_pop($chunks); | |
$chunks[$parts - 1] = array_merge($chunks[$parts - 1], $popped); | |
} | |
$output = []; | |
foreach ($chunks as $chunk) { | |
$output[] = implode(' ', $chunk); | |
} | |
return $output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example use:
string_parts('This is the most tepid thing ever');
Output:
[
"This is the",
"most tepid thing ever",
]