parables / php-utils
一组常用的辅助函数
v0.0.1
2024-05-26 22:48 UTC
Requires (Dev)
- marcocesarato/php-conventional-changelog: ^1.17
- pestphp/pest: ^2.33
README
一组便捷的PHP函数
用法
所有的 Util::method()
都暴露为全局函数。为了避免与已声明的同名字符函数冲突,全局函数被包裹在 if (! function_exists('fn_name')) {
块中。
// StringUtils normalize_whitespace(...$args) capitalize(...$args) instance_or_default(...$args) slugify(...$args) words(...$args) is_all_upper_case(...$args) pascal_case(...$args) camel_case(...$args) snake_case(...$args) kebab_case(...$args) excel_date_to_php_date(...$args) array_flatten(...$args) array_keys_transform(...$args) array_unique_value(...$args) is_url(...$args) is_valid_url(...$args)
字符串工具
normalizeWhitespace(string $str = '')
删除额外空格并修剪字符串。
$str = " This string \n has \t extra \v spaces . "; $normalizedStr = Utils::normalizeWhitespace($str); // $normalizedStr = "This string has extra spaces .";
capitalize(string $str = '')
将每个单词的首字母大写,其余字母小写。
$str = "this SENTENCE needs CAPITALIZATION!"; $capitalizedStr = Utils::capitalize($str); // $capitalizedStr = "This Sentence Needs Capitalization";
slugify(string $str = '', bool $toLower = true)
转换为URL友好的格式,使用破折号/下划线。可选的toLower控制转换为小写。
$str = "My Awesome Product Name!"; $slug = Utils::slugify($str); // $slug = "my-awesome-product-name"; $slugWithUppercase = Utils::slugify($str, false); // $slugWithUppercase = "My-Awesome-Product-Name";
words(string $str = '')
分割为单词数组,保留单个单词的大小写。
$str = "This is a sentence with multiple words."; $words = Utils::words($str); // $words = ["This", "Is", "A", "Sentence", "With", "Multiple", "Words"];
isAllUpperCase(string $str)
检查是否所有字符都是大写。
$str = "ALL UPPERCASE"; $isAllUpper = Utils::isAllUpperCase($str); // true $str = "Not All Uppercase"; $isAllUpper = Utils::isAllUpperCase($str); // false
pascalCase(string $str = '')
转换为PascalCase(所有单词都以大写字母开头)。
$str = "this is a string"; $pascalCase = Utils::pascalCase($str); // $pascalCase = "ThisIsString";
camelCase(string $str = '')
转换为camelCase(第一个单词小写,其余大写)。
$str = "This is a string"; $camelCase = Utils::camelCase($str); // $camelCase = "thisIsAString";
snakeCase(string $str = '')
转换为snake_case(小写字母,用下划线分隔)。
$str = "This is a string"; $snakeCase = Utils::snakeCase($str); // $snakeCase = "this_is_a_string";
kebabCase(string $str)
转换为kebab-case(小写字母,用连字符分隔)。
$str = "This is a string"; $kebabCase = Utils::kebabCase($str); // $kebabCase = "this-is-a-string";
isUrl(string $url)
使用内置函数进行基本的URL验证。
$url = "https://www.example.com"; $isUrlValid = Utils::isUrl($url); // true $url = "invalid-url"; $isUrlValid = Utils::isUrl($url); // false
isValidUrl(string $url)
使用解析和主机名检查进行更严格的URL验证。
$url = "https://www.example.com"; $isValidUrl = Utils::isValidUrl($url); // true $url = "invalid-url"; $isValidUrl = Utils::isValidUrl($url); // false