Created
August 4, 2012 23:43
-
-
Save mattsah/3260631 to your computer and use it in GitHub Desktop.
A better underscorize method?
This file contains hidden or 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 | |
$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