Skip to content

Instantly share code, notes, and snippets.

@mattsah
Created August 4, 2012 23:43
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 mattsah/3260631 to your computer and use it in GitHub Desktop.
Save mattsah/3260631 to your computer and use it in GitHub Desktop.
A better underscorize method?
<?php
$tests = [
'FavoriteURL',
'URLHelper',
'FavoriteURLs',
'AmazingURLsFromSpace',
'FavoriteURLHelper',
'FBIManBob',
'removeXMLTags',
'fuckItTillItFBIs'
];
function us($string) {
$rules = [
'/[a-z]([A-Z][a-z])/', // Matches words following words
'/[A-Z]+s([A-Z][a-z])/', // Matches words following pluralized acronyms
'/[a-z]([A-Z]+)/', // Matches acronyms following words
'/[A-Z]+([A-Z][a-z][^_])/', // Matches word following acronyms
];
foreach ($rules as $rule) {
if (preg_match_all($rule, $string, $matches)) {
foreach ($matches[0] as $i => $match) {
$fragment = $matches[1][$i];
$replacement = str_replace($fragment, '_' . $fragment, $match);
$string = str_replace($match, $replacement, $string);
}
}
}
return strtolower($string);
}
foreach ($tests as $test) {
echo $test . ' => ' . us($test) . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment