Skip to content

Instantly share code, notes, and snippets.

@tylerwiegand
Created March 19, 2020 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tylerwiegand/2c632bae37de36b4f9578136cb65c254 to your computer and use it in GitHub Desktop.
Save tylerwiegand/2c632bae37de36b4f9578136cb65c254 to your computer and use it in GitHub Desktop.
stringHalver
<?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;
}
@tylerwiegand
Copy link
Author

Example use:

string_parts('This is the most tepid thing ever');

Output:
[
"This is the",
"most tepid thing ever",
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment