Created
February 9, 2018 17:10
-
-
Save fdorantesm/642582d184fe38ac4ca250f72c9288c8 to your computer and use it in GitHub Desktop.
Human implode
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 | |
function human_implode($glue = ",", $last = "y", $elements = array(), $filter = null){ | |
if ($filter) { | |
$elements = array_map($filter, $elements); | |
} | |
$str = implode("{$glue} ", $elements); | |
if (count($elements) == 2) { | |
return str_replace("{$glue} ", " {$last} ", $str); | |
} | |
return preg_replace("/[{$glue}](?!.*[{$glue}])/", " {$last}", $str); | |
} |
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 | |
require 'helpers.php'; | |
print_r("<pre>"); | |
print_r(human_implode(",", "y", ["Hugo", "Paco", "Luis"])); | |
print_r("<br>"); | |
print_r(human_implode(",", "y", ["limón sin semilla", "melón chino", "jitomate saladette"], "ucfirst")); | |
print_r("<br>"); | |
print_r(human_implode(",", "y", ["chalequito matón", "pantaloncito trucutrú"], "ucwords")); | |
print_r("<br>"); | |
print_r(human_implode(",", "o", ["Guillermo Ochoa", "José de Jesús Corona", "Alfredo Talavera"], "mb_strtoupper")); | |
print_r("</pre>"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment