Skip to content

Instantly share code, notes, and snippets.

@davidon
Created November 3, 2018 22:24
Show Gist options
  • Save davidon/f9b9972a8167d0e386f96d74d85a96ea to your computer and use it in GitHub Desktop.
Save davidon/f9b9972a8167d0e386f96d74d85a96ea to your computer and use it in GitHub Desktop.
PHP: Convert a string to snake case
/**
* Convert a string to snake case.
*
* @param string $value
* @param string $delimiter Default to underscore
*
* @return string
*/
public function snake(string $value, ?string $delimiter = null): string
{
if (!\ctype_lower($value)) {
$value = (string) \preg_replace('/\s+/u', '', \ucwords($value));
$value = (string) \mb_strtolower(\preg_replace(
'/(.)(?=[A-Z])/u',
'$1' . ($delimiter ?? '_'),
$value
));
}
return $value;
}
@davidon
Copy link
Author

davidon commented Nov 3, 2018

From eoneopay/utils/src/Str.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment