el-gitto-junior / string
一组基本的字符串操作函数。
Requires
- php: ^5.4 || ^7.0
- icecave/parity: ^1.0
- voku/portable-utf8: ^3.0
Requires (Dev)
- codegyre/robo: ^0.7
- couscous/couscous: ^1.5
- icanboogie/inflector: ^1.4
- phpunit/phpunit: ^4.8
- satooshi/php-coveralls: ^1.0
- voku/anti-xss: ^2.0
- voku/urlify: ^2.0
This package is auto-updated.
Last update: 2024-09-06 23:26:16 UTC
README
一组基本的字符串操作函数。包含2个API
- 一个基于过程的API,使用命名空间函数/静态方法调用。
- 还有一个更流畅的基于对象的API。
我不会在这里详细记录每个函数,但请参见以下一些通用用法示例。其余的你可以通过阅读源代码自行解决,它相当简单,且注释详尽。
如何安装
使用composer安装很简单
composer require gears/string:*
如何使用
以下是一些过程示例
// returns true Gears\String\contains('this is a test', 'test'); // returns 'this is a test' Gears\String\between('<p>this is a test</p>', '<p>', '</p>'); // returns 'cde' Gears\String\subString('abcdeg', 2, 5);
在PHP 5.6中,您可以导入函数,所以您可以将上述代码改为
// Import the functions use function Gears\String\contains; use function Gears\String\between; use function Gears\String\subString; // returns true contains('this is a test', 'test'); // returns 'this is a test' between('<p>this is a test</p>', '<p>', '</p>'); // returns 'cde' subString('abcdeg', 2, 5);
注意:所有函数名称都是驼峰命名。
在PHP 5.6之前,这是不可能的。所以您可以这样做
// Import the string class use Gears\String as Str; // returns true Str::contains('this is a test', 'test'); // returns 'this is a test' Str::between('<p>this is a test</p>', '<p>', '</p>'); // returns 'cde' Str::subString('abcdeg', 2, 5);
工厂方法:您可能希望使用工厂方法来初始化一个新的Gears\String对象。当您这样做时,请注意后续的方法调用签名如何变化。您不再需要提供要执行操作的字符串作为第一个参数。这会自动为您完成。以下是一个示例
// using the factory method - returns true Str::s('This is a test')->contains('test'); // Method chaining is possible - returns 'this is a test' Str::s('<div><p>this is a test</p></div>') ->between('<div>', '</div>') ->between('<p>', '</p>');
例如,当使用match方法返回数组时,该数组将是Gears\String实例的数组,而不是简单的PHP字符串。
foreach (Str::s('I am going to perform a test')->match('/ \w /') as $match) { if ($match->contains('a')) { echo 'we found the letter a'; } }
注意:使用过程API将仅返回标准PHP字符串,与上述不同。
Laravel集成
Gears\String被设计成与Laravel Str类功能兼容。因此,如果您愿意,您可以将Illuminate\Support\Str
完全替换为Gears\String
。
要在/app/config/app.php
文件中这样做,替换以下行
'Str' => 'Illuminate\Support\Str',
为
'Str' => 'Gears\String',
致谢
感谢alecgorge的启发,我借鉴了他的方法,稍微重构了一下,并添加了一些自己的方法。https://github.com/alecgorge/PHP-String-Class/
此外,Laravel提供的类Illuminate\Support\Str
中的所有方法都已被集成到Gears\String
中。https://github.com/laravel/framework/blob/4.2/src/Illuminate/Support/Str.php
由Brad Jones开发 - brad@bjc.id.au