Skip to content

Instantly share code, notes, and snippets.

@Qix-
Last active August 29, 2015 14:07
Show Gist options
  • Save Qix-/3c12bab6b6d64721964e to your computer and use it in GitHub Desktop.
Save Qix-/3c12bab6b6d64721964e to your computer and use it in GitHub Desktop.
PHP cwords()
<?php
/**
* A more robust ucwords()
*/
define( 'UCW_DEFAULTS', 0x1 );
define( 'UCW_MATCHSTART', 0x2 );
define( 'UCW_REVERSE', 0x4 );
function cwords( $name, $target_char = null, $delims = '', $flags = 0x3 ) {
# At least have an empty string
$delims = is_string( $delims ) ? $delims : '';
# Use defaults?
if ( $flags & UCW_DEFAULTS ) {
$delims .= '_- .\n\t\r"\'';
}
# Fix delimiter characters
$delims = str_replace( '-', '\-', $delims );
# Build regex
$regex = '~(';
$regex .= ($flags & UCW_MATCHSTART) ? '^|' : '';
$regex .= '[' . $delims . '])([^' . $delims . ']?)~';
# Replace all
return preg_replace_callback(
$regex,
function( $matches ) use ( $target_char, $flags ) {
$str = is_null( $target_char ) || empty( $matches[1] )
? $matches[1]
: $target_char;
$casing = $flags & UCW_REVERSE
? 'strtolower'
: 'strtoupper';
$str .= $casing( $matches[2] );
return $str;
},
$name );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment