Created
November 3, 2018 22:24
-
-
Save davidon/f9b9972a8167d0e386f96d74d85a96ea to your computer and use it in GitHub Desktop.
PHP: Convert a string to snake case
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
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From eoneopay/utils/src/Str.php