Tuesday, June 07, 2011

camelize and underscore

CakePHP 的 Inflector Class 裡頭找到這段的程式碼, 非常精簡地寫法!
/**
 * Returns given $lower_case_and_underscored_word as a camelCased word.
 *
 * @param string $lower_case_and_underscored_word Word to camelize
 * @return string Camelized word. likeThis.
 * @access public
 * @static
 */
function camelize($lowerCaseAndUnderscoredWord) {
  $replace = str_replace(" ", "", ucwords(str_replace("_", " ", $lowerCaseAndUnderscoredWord)));
  return $replace;
}
/**
 * Returns an underscore-syntaxed ($like_this_dear_reader) version of the $camel_cased_word.
 *
 * @param string $camel_cased_word Camel-cased word to be "underscorized"
 * @return string Underscore-syntaxed version of the $camel_cased_word
 * @access public
 * @static
 */
function underscore($camelCasedWord) {
  $replace = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $camelCasedWord));
  return $replace;
}

No comments: