laraplus/string

字符串操作的优秀流畅接口。

1.0.3 2020-11-05 13:18 UTC

This package is auto-updated.

Last update: 2024-09-06 12:14:42 UTC


README

本包提供了一个流畅、易于使用的字符串操作接口。它与 Illuminate\Support 集成,即使在处理多个结果时也能启用流畅的语法。所有方法都支持 UTF-8。

安装

要安装此包,只需使用 composer 引入它

composer require laraplus/string

示例用法

使用此包,您可以避免丑陋的嵌套 str_* 函数和永无止境的针锋相对问题

str(' some text ')->trim()->substring(0, 4);

// instead of

substr(trim(' some text '), 0, 4);

如果您有一个 slug "my-blog-title-4" 并需要找到索引 "4",您可以简单地写入

$lastIndex = str($lastSlug)->explode('-')->last();

// instead of

$parts = $explode('-');
$lastIndex = array_pop($parts);

假设您有一些需要解析的“冒号分隔”多行字符串

str($content)->lines()->each(function ($row) {
    $data = str($row)->explode(':');
    // do something with $data here
});

// instead of

$lines = preg_split('/\r\n|\n|\r/', $content);
foreach($lines as $line) {
    $data = explode(':', $line);
    // do something with $data here
}

完整参考

初始化

您可以直接初始化 StringBuffer 对象,或者通过使用 str 辅助函数来初始化。

$string = new Laraplus\String\StringBuffer('Hello world!');

// or

$string = str('Hello world!');

链式调用

当方法调用的结果是一个字符串时,它会自动包装在一个新的 StringBuffer 实例中,因此可以链式调用方法。

// result: "HELLO"
str('hello world')->toUpper()->wordAt(0);

如果您需要展开对象,可以通过调用 get() 方法或简单地将其转换为字符串来实现。

// a string "Hello world" is produced in all examples below
str('hello world')->ucfirst()->get();
(string)str('hello world')->ucfirst();
str('hello')->ucfirst() . ' world!';

当一个方法返回一个数组时,它会自动包装在一个 Collection 对象中,这使您能够进行进一步链式调用。

str('hello world')->words()->each(function($word){
 // Be careful, $word is just a plain string here.
 // To convert it to StringBuffer again just call: str($word)
});

有关可用集合方法的完整参考,请参阅 Laravel 文档:https://laravel.net.cn/docs/5.1/collections#available-methods

可用方法

ucfirst()

将字符串的第一个字母转换为大写。

// result: "Hello world"
str('hello world')->ucfirst();

lcfirst()

将字符串的第一个字母转换为小写。

// result: "hello world"
str('Hello world')->lcfirst();

startsWith($needles)

确定字符串是否以给定的子串开头。

// returns true
str('Hello world')->startsWith('Hello');

// returns false
str('Hello world')->startsWith('world');

// returns true
str('Hello world')->startsWith(['H', 'W']);

endsWith($needles)

确定字符串是否以给定的子串结尾。

// returns true
str('Hello world')->endsWith('world');

// returns false
str('Hello world')->endsWith('Hello');

// returns true
str('Hello world')->endsWith(['o', 'd']);

contains($needles)

确定字符串是否包含给定的子串。

// returns true
str('Hello world')->contains('world');

// returns false
str('Hello world')->contains('universe');

// returns true
str('Hello world')->contains(['w', 'u']);

equals($needles)

确定字符串是否等于给定输入,进行恒定时间比较。

// returns true
str('Hello world')->equals('Hello world');

// returns false
str('Hello world')->equals('Hello universe');

matches($pattern)

确定字符串是否与给定的模式匹配。

// returns true
str('Hello/World')->matches('*/*');

// returns true
str('Hello world')->equals('Hello*');

explode($delimiters)

使用给定的分隔符分割字符串。

// result: ['Hello', ' World']
str('Hello, World')->explode(',');

// result: ['one', 'two', 'three', 'four']
str('one:two,three:four')->explode([':', ',']);

indexOf($needle, $offset = 0)

在字符串中找到给定针值的第一个出现,从提供的偏移量开始。

// returns 0
str('one, two')->indexOf('o');

// returns 7
str('one, two')->indexOf('o', 1);

lastIndexOf($needle, $offset = 0)

在字符串中找到给定针值的最后一个出现,从提供的偏移量开始。

// returns 7
str('one, two')->lastIndexOf('o');

// returns 0
str('one, two')->lastIndexOf('o', 1);

replace($search, $replace, &$count = 0)

将搜索字符串的所有出现替换为替换字符串。

// result: 'one; two; three'
str('one, two, three')->replace(',', ';');

// result: 'one; two; three' and $count in incremented by 2
str('one, two, three')->replace(',', ';', $count);

// result: 'one; two; three'
str('one, two. three')->replace([',', '.'], ';');

// result: 'one; two, three'
str('one, two. three')->replace([',', '.'], [';', ',']);

substring($start, $length = null)

返回由起始和长度参数指定的字符串部分

// result: 'world'
str('Hello world')->substring(6);

// result: 'll'
str('Hello world')->substring(2, 2);

toAscii()

将 UTF-8 值转义为 ASCII。

// result: 'CcZzSs'
str('ČčŽžŠš')->toAscii();

toCamel()

将值转换为驼峰式。

// result: 'helloWorld'
str('hello_world')->toCamel();

toSnake()

将值转换为蛇形。

// result: 'hello_world'
str('HelloWorld')->toSnake();

toStudly()

将值转换为 StudlyCase。

// result: 'HelloWorld'
str('hello_world')->toStudly();

toTitle()

将值转换为标题样式。

// result: 'Hello World'
str('hello world')->toTitle();

toSlug()

将值转换为标题样式。

// result: 'hello-world'
str('Hello world')->toSlug();

toUpper()

将给定的字符串转换为大写。

// result: 'HELLO WORLD'
str('Hello world')->toUpper();

toLower()

将给定的字符串转换为小写。

// result: 'hello world'
str('Hello World')->toLower();

toSingular()

获取英语单词的单数形式。

// result: 'person'
str('people')->toSingular();

toPlural()

获取英语单词的复数形式。

// result: 'people'
str('person')->toPlural();

length()

返回给定字符串的长度。

// returns 11
str('Hello world')->length();

words($ignore = '?!;:,.')

返回字符串中单个单词的 Collection。

// result: ['one', 'two', 'three']
str('one, two, three')->words();

// result: ['one', 'two', 'three']
str('(one) : (two) : (three)')->words('(:)');

lines()

返回字符串中单个行的集合。

// result: ['one', 'two', 'three']
str("one\ntwo\r\nthree")->lines();

prepend($string)

在字符串前添加给定输入。

// result: 'hello world'
str('world')->prepend(' ')->prepend('hello');

append($string)

在字符串后添加给定输入。

// result: 'hello world'
str('hello')->append(' ')->append('world');

trim($chars = null)

从字符串两端移除指定字符。如果没有提供字符,则移除所有空白字符。

// result: 'hello world'
str('  hello world  ')->trim();

// result: 'hello world'
str('--hello world--')->trim('-');

ltrim($chars = null)

类似于 trim(),但只从左侧移除字符。

// result: 'hello world  '
str('  hello world  ')->ltrim();

// result: 'hello world--'
str('--hello world--')->ltrim('-');

rtrim($chars = null)

类似于 trim(),但只从右侧移除字符。

// result: '  hello world'
str('  hello world  ')->rtrim();

// result: '--hello world'
str('--hello world--')->rtrim('-');

limit($limit = 100, $end = '...')

限制字符串中的字符数量。

// result: 'hello...'
str('hello world')->limit(5);

// result: 'hello etc.'
str('hello world')->limit(5, ' etc.');

limitWords($limit = 100, $end = '...')

限制字符串中的单词数量。

// result: 'hello the world...'
str('Hello the world of PHP!')->limitWords(3);

// result: 'hello the world etc.'
str('Hello the world of PHP!')->limitWords(3, ' etc.');

wordAt($index)

返回指定索引处的单词。

// result: 'world'
str('Hello the world of PHP!')->wordAt(2);

tree($open = '{', $close = '}')

使用给定的分隔符解析树结构。

//result: ['one', ['two', ['three'], 'four']]
str('one{two{three}four}')->tree();

使用偏移量

由于 StringBuffer 类实现了 ArrayAccess 接口,因此您也可以使用所有常规的偏移量功能。

$string = str('hello world');
$string[0]; // returns 'h'
isset($string[10]) // returns true
unset($string[0]); // $string becomes 'ello world'
$string[0] = 'He'; // $string becomes 'Hello world'