Skip to content

Instantly share code, notes, and snippets.

@nosilex
Created June 30, 2018 15:02
Show Gist options
  • Save nosilex/8bf9ec311d60b8b4ad78275b6d64a203 to your computer and use it in GitHub Desktop.
Save nosilex/8bf9ec311d60b8b4ad78275b6d64a203 to your computer and use it in GitHub Desktop.
Capitalize an string to correct format
<?php
/**
* Capitalize an string|array
* Ex: Fred El BRAVO => Fred el Bravo
* Empresa Xpto s/a => Empresa Xpto S/A
*
* @param string|array $input
* @param array $exclude {If passed an array, exclude any element}
*
* @return string|array
*/
function capitalize($input, $exclude = [])
{
if (is_array($input)) {
$fn = function (&$value, $key) use ($exclude) {
$value = !in_array($key, $exclude) ? capitalize($value) : $value;
};
array_walk(
$input,
$fn
);
return $input;
} else {
$arr = [
'da' => 'da', 'das' => 'das', 'de' => 'de', 'di' => 'di', 'do' => 'do', 'dos' => 'dos', 'e' => 'e', 'el' => 'el',
'i' => 'I', 'ii' => 'II', 'iii' => 'III', 'iv' => 'IV', 'v' => 'V', 'vi' => 'VI', 'vii' => 'VII', 'viii' => 'VIII',
'ix' => 'IX', 'x' => 'X', 'xi' => 'XI', 'xii' => 'XII', 'xiii' => 'XIII', 'a/c' => 'A/C', 'ltda' => 'LTDA',
'me' => 'ME', 'eireli' => 'EIRELI', 'epp' => 'EPP', 's/a' => 'S/A', 's.a' => 'S/A', 's.a.' => 'S/A',
];
$fn = function ($word) use ($arr) {
return (!array_key_exists($word, $arr)) ? mb_convert_case(trim($word), MB_CASE_TITLE, 'utf-8') : $arr[$word];
};
return join(' ',
array_map(
$fn,
explode(
' ',
mb_strtolower(trim($input), 'utf-8')
)
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment