basteyy / php-stringer
一个简单的 PHP 类,提供了一些字符串操作函数、生成随机字符串以及与时间/日期对象交互的功能。
Requires
- php: ^8.2
Requires (Dev)
- phpunit/phpunit: ^10.4
This package is auto-updated.
Last update: 2024-09-23 11:11:14 UTC
README
每个开发者都知道这一过程:这里我需要一个随机字符串,那里我需要从一个输入生成一个 URL,然后我想知道一个事件有多久了。这个包捆绑了一些我在项目中不断需要的函数。欢迎您贡献并扩展它。
安装
composer require basteyy/php-stringer
用法
要在项目中使用 basteyy\php-stringer
包,以下是一些示例及其预期输出
字符串操作
转义字符串
为了在 HTML 上下文中安全地输出字符串,使用 escapeString
echo basteyy\Stringer\escapeString('<script>alert("hello")</script>'); // Output: <script>alert("hello")</script>
生成哈希值
使用 getStringHashSum
创建字符串的哈希值(默认算法为 SHA256)
echo basteyy\Stringer\getStringHashSum('yourStringHere'); // Output: [sha256 hash of 'yourStringHere']
删除双斜杠
使用 remove_double_slashes
清理文件路径或 URL
echo basteyy\Stringer\remove_double_slashes('https://example.com//path//'); // Output: https://example.com/path/
生成短链接文本
使用 getSlugifiedText
将字符串转换为 URL 优化的版本
echo basteyy\Stringer\getSlugifiedText('Hello World! How are you?'); // Output: hello-world-how-are-you
生成短链接(已弃用)
为了向后兼容,slugify
仍然可用,但已弃用。它与 getSlugifiedText
功能相同
echo basteyy\Stringer\slugify('This is a Test String!'); // Output: this-is-a-test-string
随机字符串生成
生成字母数字字符串
echo basteyy\Stringer\getRandomAlphaNumericString(10); // Output example: "1a2b3c4d5e"
生成数字字符串
echo basteyy\Stringer\getRandomNumericString(10); // Output example: "1234567890"
生成字母字符串
echo basteyy\Stringer\getRandomAlphaString(10); // Output example: "aBcDeFgHiJ"
生成包含自定义字符的字符串
echo basteyy\Stringer\getRandomString(10, '!@#$%^&*()'); // Output example: "%$@!^&*!@"
创建易记密码
在 basteyy\Stringer 库中,createMemorablePassword
函数生成易于记住的密码,结合单词、数字和符号。此函数不是密码学安全的,更适合用于用户友好的密码,而不是高安全用途。
$password = basteyy\Stringer\createMemorablePassword(2, 2, 2, true); echo $password;
在此示例中,该函数生成一个包含
- 从预定义列表中随机选择的 2 个单词。
- 2 个随机数字。
- 从默认符号集 !@#$%^&* 中随机选择的 2 个符号。
- 将密码转换为小写。
输出将是一个类似于 apple7%cloud4*
的字符串,使其易于记忆且独特。您可以按需调整单词、数字和符号的数量。
注意:函数
createMemorablePassword
不是密码学安全的,不应用于高安全场景。
时间操作
获取“不久前”的时间
getNiceTimeAgo
函数返回从当前时间到提供的 DateTime 的人读时间差。
// Standard usage with default unit names echo basteyy\Stringer\Times\getNiceTimeAgo('2023-01-01 00:00:00'); // Output example: "2 months ago" // Exact output echo basteyy\Stringer\Times\getNiceTimeAgo('2023-01-01 00:00:00', true); // Output example: "2 months, 3 days, 4 hours, 5 minutes, 6 seconds ago" // Custom unit names $customUnitMap = [ 'second' => ['Sekunde', 'Sekunden'], 'minute' => ['Minute', 'Minuten'], // ... other units ]; echo basteyy\Stringer\Times\getNiceTimeAgo('2023-01-01 00:00:00', false, $customUnitMap); // Output example: "2 Monate ago"
以下示例展示了 getNiceTimeAgo
函数的灵活性,提供了精确时间间隔、自定义单位名称和本地化的选项。