lucleroy/php-strings

用于操作字符串的 PHP 库。

0.1.0 2018-09-19 08:47 UTC

This package is not auto-updated.

Last update: 2024-09-27 13:53:59 UTC


README

用于操作字符串的 PHP 库。

目录

介绍

这个库提供了一种统一的方式来管理二进制字符串和 Unicode 字符串。

use function LucLeroy\Strings\s;
use function LucLeroy\Strings\u;

echo s('Hello')->upper()->reverse();        // OLLEH

echo u('Доброе утро.')->upper()->reverse(); // .ОРТУ ЕОРБОД

你可以处理大小写敏感或不敏感的字符串。

use function LucLeroy\Strings\s;

echo s('Hello World')->contains('hello') ? 'true' : 'false';                      // false

echo s('Hello World')->toCaseInsensitive()->contains('hello') ? 'true' : 'false'; // true

此外,它还提供了强大的子字符串处理方法。

use function LucLeroy\Strings\s;

echo s('Hello World')->explode(' ')->reverse()->patch(); // olleH dlroW

需求

  • PHP 7。
  • mbstring 扩展。
  • intl 扩展。

安装(使用 Composer)

将以下内容添加到 composer.json 文件的 require 部分

"lucleroy/php-strings": "*"

然后运行 composer update

用法

基础

此库提供了四个主要类,实现了 StringInterface

  • CaseSensitiveBinaryString 用于处理大小写敏感的二进制字符串。
  • CaseInsensitiveBinaryString 用于处理大小写不敏感的二进制字符串。
  • CaseSensitiveUnicodeString 用于处理大小写敏感的 Unicode 字符串。
  • CaseInsensitiveUnicodeString 用于处理大小写不敏感的 Unicode 字符串。

重要说明:这些类是不可变的。

使用 create 方法创建字符串

use LucLeroy\Strings\CaseSensitiveBinaryString;

$str = CaseSensitiveBinaryString::create('Hello');

默认情况下,Unicode 字符串使用 UTF-8 编码。如果您想使用其他编码,可以在 create 函数的第二个参数中指定它。您可以使用任何由 mbstring 扩展支持的编码(不一定是 Unicode 编码)。

use LucLeroy\Strings\CaseSensitiveUnicodeString;

$str = CaseSensitiveUnicodeString::create('Hello…', 'HTML-ENTITIES');

echo $str->append(' World!')->upper();   // HELLO… WORLD!

您可以使用 toCaseSensitivetoCaseInsensitivetoBinarytoUnicode 方法将任何类型的字符串转换为其他类型的字符串。

您可以直接使用函数 s(用于二进制字符串)和 u(用于 Unicode 字符串)。这些函数分别是 CaseSensitiveBinaryString:createCaseSensitiveUnicodeString:create 的快捷方式。

处理单个子字符串

乍一看,这个库似乎没有提供搜索或提取子字符串的方法。这当然是错误的。但是,处理子字符串的方式有些特别。

要处理子字符串,您必须首先调用 select 方法,这将创建一个构建器(不可变)。

$str = s('Hello World!');

$builder = $str->select();

然后您可以使用构建器方法选择子字符串。

$builder = $builder->first('World'); // select the substring 'World'

然后您可以使用 selectionstartendlength 获取子字符串的位置信息。

echo $builder->start();              // 6
echo $builder->end();                // 11
echo $builder->length();             // 5
$selection = $builder->selection();  // $selection = [6, 11]

注意:选择的结束是选择后的第一个索引。

您还可以使用 patch 修改子字符串或使用 remove 删除它。

echo $builder->patch('Everybody');  // Hello Everybody!
echo $builder->remove();            // Hello !

您可以使用 build 提取子字符串。

$substring = $builder->build();

echo $substring;  // World

由于 build 返回与原始字符串相同类型的实例,您可以然后转换子字符串。

$substring = $substring->upper();  

echo $substring;  // WORLD

最后,您可以使用 patch 将修改后的子字符串重新注入到原始字符串中。

echo $substring->patch();  // Hello WORLD!

当然,您可以链式操作。

echo s('Hello World!')
    ->select()
    ->first('World')
    ->build()
    ->upper()
    ->patch();  // Hello WORLD!

处理多个子字符串

某些方法(如 explodesplitoccurences 等)返回多个子字符串。结果是实现了 SubstringListInterface 的类的实例,它扩展了 StringInterface,因此您可以在这些方法的输出上使用所有可用于字符串的方法。

$str = s('hello world!');

$list = $str->occurences(['h', 'w'])->upper();

然后使用 patch 用修改后的子字符串修补原始字符串。

echo $list->patch(); //  Hello World!

如果您不关心原始字符串,您可以使用 toArray 作为 StringInterface 的数组检索子字符串。您还可以使用 implode 将子字符串连接成一个单独的 StringInterface

情况转换器

如果您想将字符串转换为驼峰式、帕斯卡式等,必须使用 caseTransform。此方法的参数必须实现 CaseTransformerInterface(在命名空间 LucLeroy\Strings\CaseTransformer 中)。常用的转换器可以通过 CaseTransformerFactory 获取。

use LucLeroy\Strings\CaseTransformer\CaseTransformerFactory;
use function LucLeroy\Strings\s;

$str = s('Hello World!');

$factory = CaseTransformerFactory::getInstance();

echo $str->caseTransform($factory->camel());   // helloWorld

echo $str->caseTransform($factory->pascal()); // HelloWorld

echo $str->caseTransform($factory->pascal()); // HELLO_WORLD

caseTransform 仅保留字母序列和数字序列,并将这些序列作为 StringInterface 的数组提供。CaseTransformerInterface 有一个 transform 方法,该方法将此数组转换为一个 StringInterface

要实现自己的转换器,您可以直接实现 CaseTransformerInterface

大多数情况下,您可以根据序列本身及其两侧的序列来确定如何呈现该序列。例如,在驼峰式中,第一个序列必须是小写的,其他序列也必须是小写的,除了第一个字符,它必须是大写的。您可以通过扩展 AbstractContextCaseTransformer 来实现仅依赖于上下文的情况转换器。您必须实现 transformPart 方法,该方法有三个参数:当前部分、上一个部分和下一个部分。以下是一个基本的驼峰式转换器实现示例

use LucLeroy\Strings\CaseTransformer\AbstractContextCaseTransformer;
use LucLeroy\Strings\StringInterface;
use function LucLeroy\Strings\s;

class CamelCaseTransformer extends AbstractContextCaseTransformer
{

    public function transformPart(
        StringInterface $current, 
        StringInterface $previous = null,
        StringInterface $next = null
    ) {
        if ($previous) {
            return $current->titleize();
        } else {
            return $current->lower();
        }
    }

}

echo s('Hello World!')->caseTransform(new CamelCaseTransformer());  // helloWorld

但是还有更简单的方法:您可以使用 SimpleCaseTransformer 类创建一个情况转换器。您可以将之前的驼峰式转换器重写如下

use LucLeroy\Strings\CaseTransformer\SimpleCaseTransformer;
use function LucLeroy\Strings\s;

$camelCaseTransformer = new SimpleCaseTransformer(
    SimpleCaseTransformer::CASE_TITLE, 
    SimpleCaseTransformer::CASE_LOWER
);

echo s('Hello World!')->caseTransform($camelCaseTransformer);

使用 SimpleCaseTransformer,您可以指定第一个序列和其他序列的不同情况,以及不同类型序列(字母或数字)之间的不同分隔符。

参考

字符串

alignLeft($size, $fill = ' '): StringInterface

返回一个最小尺寸的左对齐字符串。剩余的空间用字符串 $fill 填充;

echo s('Hello')->alignLeft(10);        // 'Hello     '
echo s('Hello')->alignLeft(10, '.');   // 'Hello.....'
echo s('Hello')->alignLeft(10, '+-');  // 'Hello+-+-+'

alignRight($size, $fill = ' '): StringInterface

返回一个最小尺寸的右对齐字符串。剩余的空间用字符串 $fill 填充;

echo s('Hello')->alignRight(10);        // '     Hello'
echo s('Hello')->alignRight(10, '.');   // '.....Hello'
echo s('Hello')->alignRight(10, '+-');  // '+-+-+Hello'

append($string): StringInterface

$string 添加到当前字符串的末尾。

echo s('Hello')->append(' World!');  // Hello World!

ascii(): UnicodeStringInterface

仅适用于Unicode字符串。

将字符串转换为ASCII。

echo u('Доброе утро.')->ascii();  // Dobroe utro.

caseTransform($transformer): StringInterface

将字符串转换为驼峰式、Pascal式、kebab式等。

use LucLeroy\Strings\CaseTransformer\CaseTransformerFactory;
use function LucLeroy\Strings\s;

$factory = CaseTransformerFactory::getInstance();
$camel = $factory->camel();

echo s('Hello World!')->caseTransform($camel);  // helloWorld

charAt($index): string

返回指定索引处的字符,作为普通字符串。

echo s('Hello')->charAt(1);   // 'e'

center($size, $fill = ' '): StringInterface

返回一个最小尺寸的居中字符串。剩余的空间用字符串 $fill 填充;

echo s('Hello')->center(10);        // '  Hello   '
echo s('Hello')->center(10, '.');   // '..Hello...'
echo s('Hello')->center(10, '+-');  // '+-Hello+-+'

chars(): string[]

返回组成字符串的字符,作为普通字符串数组。

$chars = s('Hello')->chars;   // $chars = ['H', 'e', 'l', 'l', 'o']

clear(): StringInterface

返回一个空字符串。

echo s('Hello')->clear;   // ''

contains($substring): bool

确定 $substring 是否是当前字符串的子串。

echo s('Hello World!')->contains('Hello') ? 'true' : 'false';  // true

containsAll($substrings): bool

确定所有 $substring 是否都是当前字符串的子串。

echo s('Hello World!')->containsAll(['Hello', 'World]) ? 'true' : 'false';  // true
echo s('Hello World!')->containsAll(['Hello', 'Everybody]) ? 'true' : 'false';  // false

containsAny($substrings): bool

确定 $substring 中是否有任何一个是当前字符串的子串。

echo s('Hello World!')->containsAny(['Hello', 'World]) ? 'true' : 'false';  // true
echo s('Hello World!')->containsAny(['Hello', 'Everybody]) ? 'true' : 'false';  // true

convert($callable)

将自定义转换应用于字符串。结果可以是任何内容。

echo u('Доброе утро.')->convert(function ($s) {
    return strlen($s);
});  // 22 (number)   

countOf($substring): int

返回 $substring 在当前字符串中出现的次数。

echo s('To be or not to be.')->countOf('be');  // 2

cut($cuts): SubstringListInterface

返回一个包含当前字符串切割到指定位置的 SubstringListInterface

$result = s('Hello World!')->cut([5, 6, 11])->toString();  // $result = ['Hello', ' ', 'World', '!']

endsWith($substring): bool

确定当前字符串是否以 $substring 结尾。

echo s('Hello World!')->endsWith('Hello') ? 'true' : 'false';  // false
echo s('Hello World!')->endsWith('World!') ? 'true' : 'false'; // true

endsWithAny($substrings): bool

确定当前字符串是否以 $substrings 中的任何一个结尾。

echo s('Hello World!')->endsWithAny(['Everybody!', 'World!']) ? 'true' : 'false';  // true

ensureLeft($substring): StringInterface

如果当前字符串不以 $substring 开头,则在当前字符串的开头添加 $substring

echo s('Hello World!')->ensureLeft('Hello');  // Hello World!
echo s(' World!')->ensureLeft('Hello');       // Hello World!

ensureRight($substring): StringInterface

如果当前字符串不以 $substring 结尾,则在当前字符串的末尾添加 $substring

echo s('Hello World!')->ensureRight('World!');  // Hello World!
echo s('Hello ')->ensureRight('World!');        // Hello World!

escapeControlChars(): StringInterface

转义控制字符。

echo s("Hello\nWorld!")->escapeControlChars();  // Hello\nWorld!

explode($delimiter, $limit = PHP_INT_MAX): SubstringListInterface

按分隔符拆分字符串。

$result = s('123,456,789')->explode(',')->toString();  // $result = [123, 456, 789]

注意:对于不区分大小写的字符串,所有版本的分隔符都被替换为给定版本

echo s('123o456O789')->toCaseInsensitive()->explode('o')->patch();  // 123o456o789

getEncoding(): string

仅适用于Unicode字符串。

返回字符串的编码。

echo u('Hello')->getEncoding();  // UTF-8

is($string): bool

确定字符串是否等于 $string

echo s('Hello World!')->is('Hello World!') ? 'true' : 'false';                       // true
echo s('Hello World!')->is('hello world!') ? 'true' : 'false';                       // false
echo s('Hello World!')->toCaseInsensitive()->is('hello world!') ? 'true' : 'false';  // true

isAny($strings): bool

确定字符串是否为 $strings 中的任何一个。

echo s('Hello')->isAny(['hello', 'world']) ? 'true' : 'false';                       // false
echo s('Hello')->toCaseInsensitive()->isAny(['hello', 'world']) ? 'true' : 'false';  // true

isAscii(): bool

判断字符串是否只包含ASCII字符。

echo u('Hello.')->isAscii() ? 'true' : 'false';        // true
echo u('Доброе утро.')->isAscii() ? 'true' : 'false';  // false

isEmpty(): bool

判断字符串是否为空。

echo s('Hello.')->isEmpty() ? 'true' : 'false';           // false
echo s('Hello.')->clear()->isEmpty() ? 'true' : 'false';  // true

isSubstringOf($string): bool

判断字符串是否是 $string 的子串。

echo s('Hello')->isSubstringOf('Hello World!') ? 'true' : 'false';  // true

isSubstringOfAll($strings): bool

判断字符串是否是 $strings 中每个字符串的子串。

echo s('Hello')->isSubstringOfAll('Hello World!', 'Hello Everybody!') ? 'true' : 'false';       // true
echo s('Hello')->isSubstringOfAll('Hello World!', 'Good Morning, Vietnam') ? 'true' : 'false';  // false

isSubstringOfAny($strings): bool

判断字符串是否是 $strings 中任意一个字符串的子串。

echo s('Hello')->isSubstringOfAny('Hello World!', 'Good Morning, Vietnam') ? 'true' : 'false';  // true

length(): int

返回字符串的长度。

echo s('Hello')->length();  // 5

lines(): SubstringListInterface

将字符串分割成行。支持的换行符有:"\n", "\r\n", "\r"。

$lines = s("Hello\nWorld!")->lines()->toString();  // $line s= ['Hello', 'World!']

lower(): StringInterface

将字符串转换为小写。

echo s("HELLO")->lower();  // hello

lowerFirst(): StringInterface

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

echo s("HELLO")->lower();  // hELLO

occurrences($substrings): SubstringListInterface

返回 $substrings 中所有字符串的匹配项。

echo s('Hello World!')->occurences(['o', 'l'])->implode();  // llool

patch(): StringInterface

将子串的更改应用到父字符串上。如果字符串不是子串,则返回 $this

echo s('Hello World!')
    ->select()->beforeNext(' ')->build()
    ->upper()->patch();  // HELLO World!

prepend($string): StringInterface

$string 添加到当前字符串的开头。

echo s('World!')->prepend('Hello ');  // 'Hello World!'

repeat($multiplier = 2): StringInterface

返回重复 $multiplier 次的字符串。

echo s('+-')->repeat(5);  // +-+-+-+-+-

repeatToSize($size): StringInterface

重复字符串直到达到指定的大小。

echo s('+-')->repeatToSize(15);  // +-+-+-+-+-+-+-+

replace($string): StringInterface

将当前字符串替换为 $string

echo s('Hello')->replace('Good Morning');  // Good Morning

replaceAll($search, $replace): StringInterface

将所有 $search 字符串替换为 $replace 字符串。与 PHP 函数 str_replace 的工作方式相同。

echo s('Hello World')->replaceAll(['o', 'l'], '*');  // He*** W*r*d

reverse()

反转字符串中的字符。

echo s('Hello World!')->reverse();  // !dlroW olleH

select($offset = 0): SubstringBuilder

从指定的 $offset 开始选择子串。

separate($delimiters): SubstringListInterface

通过多个分隔符分割字符串。

echo s('123 456,789')->separate([' ', ','])->reverse()->patch();  // 321 654,987

shuffle(): StringInterface

随机打乱字符串。

echo s('Hello World!')->shuffle();  // rloodl!He lW

split($size = 1): SubstringListInterface

将字符串分割成具有 $size 个字符的子串。

echo s('Hello World!')->split(3)->implode('|');  // Hel|lo |Wor|ld!

squeeze($char = ' '): StringInterface

将连续出现的 $char 替换为一个字符。

echo s('Hello    World!')->squeeze();  // Hello World!

startsWith($substring): bool

判断字符串是否以 $substring 开头。

echo s('Hello World!')->startsWith('Hello') ? 'true' : 'false';  // true
echo s('Hello World!')->startsWith('World!') ? 'true' : 'false'; // false

startsWithAny($substrings): bool

判断字符串是否以 $substrings 中的任意一个字符串开头。

echo s('Hello World!')->startsWithAny(['Everybody!', 'World!']) ? 'true' : 'false';  // true

surroundWith($string1, $string2 = null): StringInterface

$string1 添加到字符串的开头,并将 $string2(如果 $string2null,则使用 $string1)添加到末尾。

echo s('Hello World!')->surroundWith('"', '"');  // "Hello World!"

titleize(): StringInterface

将每个单词的第一个单词转换为大写,其余单词转换为小写。

echo s('hELLO world!')->titleize();  // Hello World!

toString(): string

将字符串转换为普通字符串。

echo s('Hello World!')->toString();  // Hello World!

toBinary(): BinarfyStringInterface

仅适用于Unicode字符串。

将 Unicode 字符串转换为二进制字符串。

$str = u('Доброе утро.');
echo $str->length();              // 12
echo $str->toBinary()->length();  // 22

toCaseSensitive(): CaseSensitiveInterface

仅适用于不区分大小写的字符串。

将不区分大小写的字符串转换为区分大小写的字符串。

$str = u('Hello World!')->toCaseInsensitive();
echo $str->startsWith('hello') ? 'true' : 'false';                     // true
echo $str->toCaseSensitive()->startsWith('hello') ? 'true' : 'false';  // false

toCaseInsensitive(): CaseInsensitiveInterface

仅适用于区分大小写的字符串。

将区分大小写的字符串转换为不区分大小写的字符串。

$str = u('Hello World!');
echo $str->startsWith('hello') ? 'true' : 'false';                       // false
echo $str->toCaseInsensitive()->startsWith('hello') ? 'true' : 'false';  // true

toEncoding($encoding): UnicodeStringInterface

仅适用于Unicode字符串。

修改字符串的编码。

echo u('«Hello World!»')->toEncoding('HTML');  // «Hello World!»

toUnicode($encoding = 'UTF-8'): UnicodeStringInterface

仅适用于二进制字符串。

将二进制字符串转换为指定 $encoding 的 Unicode 字符串。

$str = s('Доброе утро.');
echo $str->length();               // 22
echo $str->toUnicode()->length();  // 12

transform($callable): StringInterface

对字符串应用自定义转换。结果必须与当前字符串类型相同。如果不是,则进行转换。

echo s('Hello World')->transform(function ($s) {
    return md5($s);
})->upper();  //  B10A8DB164E0754105B7A99BE72E3FE5

trim($charlist = null): StringInterface

如果 $charlist 不是 null,则从字符串的起始和结束处删除空白或字符。

echo s('***Hello World!***')->trim('*');  // Hello World!

trimLeft($charlist = null): StringInterface

如果 $charlist 不是 null,则从字符串的起始处删除空白或字符。

echo s('***Hello World!***')->trimLeft('*');  // Hello World!***

trimRight($charlist = null): StringInterface

如果 $charlist 不是 null,则从字符串的结束处删除空白或字符。

echo s('***Hello World!***')->trimRight('*');  // ***Hello World!

truncate($size, $string = ''): StringInterface

从右侧截断到 $size 个字符。如果 $string 不为空,则用它替换被删除的字符(删除额外的字符,以确保字符串长度不超过指定的大小)。

echo s('Hello World!')->truncate(8, '...'); // Hello...

truncateLeft($size, $string = ''): StringInterface

从左侧截断到 $size 个字符。如果 $string 不为空,则用它替换被删除的字符(删除额外的字符,以确保字符串长度不超过指定的大小)。

echo s('Hello World!')->truncateLeft(8, '...'); // ...orld!

truncateMiddle($size, $string = ''): StringInterface

从中间截断到 $size 个字符。如果 $string 不为空,则用它替换被删除的字符(删除额外的字符,以确保字符串长度不超过指定的大小)。

echo s('Hello World!')->truncateMiddle(8, '...'); // He...ld!

upper(): StringInterface

将字符串转换为大写。

echo s("hello")->lower();  // HELLO

upperFirst(): StringInterface

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

echo s("hello")->lower();  // Hello

子字符串构建器

要创建子字符串构建器,请使用字符串上的 select 方法。子字符串构建器的方 法允许您为子字符串设置起始索引和结束索引。

注意:

  • 结束索引对应于第一个排除字符的索引。
  • 如果您向 select 方法提供偏移量,则索引从该偏移量开始编号。例如,如果偏移量为 5,则子字符串构建器中的索引 2 对应于字符串中的索引 7。

after($index): SubstringBuilderInterface

将起始索引移动到 $index 之后。

echo s('foo,bar')->select()->after(3);  // bar

afterFirst($substring): SubstringBuilderInterface

将起始索引移动到 $substring 首次出现的最后一个字符之后。

echo s('foo,bar,foo,baz')->select()->afterFirst('foo');  // ,bar,foo,baz

afterLast($substring): SubstringBuilderInterface

将起始索引移动到 $substring 最后一次出现的最后一个字符之后。

echo s('foo,bar,foo,baz')->select()->afterLast('foo');  // ,baz

at($index): SubstringBuilderInterface

将起始索引和结束索引移动到 $index。选择为空。在特定位置插入字符串很有用。

echo s('foo,bar')->select()->at(3)->patch(',baz');  // foo,baz,bar

atEndOfFirst($substring): SubstringBuilderInterface

将起始索引和结束索引移动到$substring首次出现后的最后一个字符。选择区域为空。用于在特定子字符串后插入字符串。

echo s('foo,bar,foo')->select()->atEndOfFirst('foo')->patch(',baz');  // foo,baz,bar,foo

atEndOfLast($substring): SubstringBuilderInterface

将起始索引和结束索引移动到最后一次出现$substring后的最后一个字符。选择区域为空。用于在特定子字符串后插入字符串。

echo s('foo,bar,foo')->select()->atEndOfLast('foo')->patch(',baz');  // foo,bar,foo,baz

atStartOfFirst($substring): SubstringBuilderInterface

将起始索引和结束索引移动到$substring首次出现的第一个字符。选择区域为空。用于在特定子字符串前插入字符串。

echo s('foo,bar,foo')->select()->atStartOfFirst('foo')->patch('baz,');  // baz,foo,bar,foo

atStartOfLast($substring): SubstringBuilderInterface

将起始索引和结束索引移动到最后一次出现$substring的第一个字符。选择区域为空。用于在特定子字符串前插入字符串。

echo s('foo,bar,foo')->select()->atStartOfLast('foo')->patch('baz,');  // foo,bar,baz,foo

before($index): SubstringBuilderInterface

将结束索引移动到指定的索引。

echo s('foo,bar')->select()->before(3);  // foo

beforeLast($substring): SubstringBuilderInterface

将结束索引移动到最后一次出现$substring的第一个字符。

echo s('foo,bar,foo')->select()->beforeLast('foo');  // foo,bar,

beforeNext($substring, $includeStart = false): SubstringBuilderInterface

将结束索引移动到当前起始索引后第一次出现$substring的第一个字符。如果$includeStarttrue,则从起始索引开始搜索。否则,从下一个字符开始搜索。

echo s('foo,bar,foo,bar')->select()->beforeNext('bar');        // foo,
echo s('foo,bar,foo,bar')->select()->beforeNext('foo');        // foo,bar,
echo s('foo,bar,foo,bar')->select()->beforeNext('foo', true);  // <empty string>

betweenSubstrings($open, $close, $match = false): SubstringBuilderInterface

如果$matchfalse,将起始索引和结束索引移动,以便选择以$open开头并以$close结尾的第一个子字符串。

如果$matchtrue,将起始索引和结束索引移动,以便选择以$open开头并以$close结尾且匹配$open的第一个子字符串。

echo s('foo,(bar,(foo),bar')->select()->betweenSubstrings('(', ')', true);  // (foo)
echo s('foo,(bar,(foo),bar')->select()->betweenSubstrings('(', ')');        // (bar,(foo)

build(): StringInterface

从选择区域创建一个StringInterface

echo s('foo,bar,baz')->select()->first('bar')->build()->upper();  // BAR

end(): int

返回选择区域的结束索引。

echo s('foo,bar,baz')->select()->first('bar')->end();  // 7

first($substring): SubstringBuilderInterface

选择$substring首次出现。

echo s('foo,bar,foo,bar')->select()->first('bar')->patch('***');  // foo,***,foo,bar

from($index): SubstringBuilderInterface

将起始索引移动到$index

echo s('foo,bar')->select()->from(3);  // ,bar

fromFirst($substring): SubstringBuilderInterface

将起始索引移动到$substring首次出现的第一个字符。

echo s('foo,bar,baz')->select()->fromFirst(',');  // ,bar,baz

fromLast($substring): SubstringBuilderInterface

将起始索引移动到最后一次出现$substring的第一个字符。

echo s('foo,bar,baz')->select()->fromLast(',');  // ,baz

fromLeft(): SubstringBuilderInterface

将起始索引移动到字符串的开始。

echo s('foo,bar')->select()->from(3)->fromLeft();  // foo,bar

fromLength($length): SubstringBuilderInterface

将起始索引移动,以便选择区域的长度为$length

echo s('foo,bar,baz')->select()->beforeLast(',')->fromLength(3);  // bar

grow($count): SubstringBuilderInterface

将当前选择区域在每侧扩展$count个字符。

echo s('foo,bar,baz')->select()->afterFirst(',')->beforeNext(',')->grow(1);  // ,bar,

insideSubstrings($open, $close, $match = false): SubstringBuilderInterface

如果$matchfalse,将起始索引和结束索引移动,以便选择由$open开头并由$close结尾的第一个子字符串。

如果$matchtrue,将起始索引和结束索引移动,以便选择由$open开头并由$close结尾且匹配$open的第一个子字符串。

echo s('foo,(bar,(foo),bar')->select()->insideSubstrings('(', ')', true);  // foo
echo s('foo,(bar,(foo),bar')->select()->insideSubstrings('(', ')');        // bar,(foo

isEmpty(): bool

判断当前选择是否为空。

echo s('foo,bar')->select()->first('baz')->isEmpty() ? 'true' : 'false';  // true
echo s('foo,bar')->select()->from(10)->to(15)->isEmpty() ? 'true' : 'false';       // true
echo s('foo,bar')->select()->from(3)->to(5)->isEmpty() ? 'true' : 'false';         // false

last($substring): SubstringBuilderInterface

选择 $substring 的最后一个出现。

echo s('foo,bar,foo,bar')->select()->last('bar')->patch('***');  //  foo,bar,foo,***

length(): int

返回选择的长度。

echo s('foo,bar,baz')->select()->first('bar')->length();  // 3

longestCommonPrefix($string): SubstringBuilderInterface

选择当前字符串和 $string 的最长公共前缀,从每个字符串的开始处开始。

echo s('foo,bar,baz')->select()->longestCommonPrefix('foo,baz,bar');  // foo,ba

longestCommonSubstring($string): SubstringBuilderInterface

选择当前字符串和 $string 的最长公共子串。

echo s('foo,bar,baz')->select()->longestCommonSubstring('bar,baz,foo');  // bar,baz

longestCommonSuffix($string): SubstringBuilderInterface

选择当前字符串和 $string 的最长公共后缀,结束于每个字符串的末尾。

echo s('foo,bar,baz')->select()->longestCommonSuffix('bar,foo,baz');  // ,baz

patch($patch): StringInterface

返回一个 StringInterface,其中选择被 $patch 替换。

echo s('foo,bar,baz')->select()->first('bar')->patch('***');  // foo,***,baz

remove(): StringInterface

返回一个 StringInterface,其中选择已被移除。

echo s('foo,bar,baz')->select()->first('bar')->remove('');  // foo,,baz

select($offset = 0): SubstringBuilderInterface

从当前选择开始一个新的选择。它相当于先执行 build 然后执行 select

echo s('foo,bar,baz')->select()->afterFirst(',')->select()->afterFirst(',');  // baz

selection(): array | null

如果选择有效,返回一个数组,包含按照顺序排列的起始索引和结束索引。如果选择无效(例如,尝试选择一个不存在的子串),返回 null

$selection = s('foo,bar,baz')->select()->first('bar')->selection();  // $selection = [4, 7] 

shiftLeft($count): SubstringBuilderInterface

将起始索引从 $count 个字符处移动。 $count 可以是负数。

echo s('foo,bar,baz')->select()->from(5)->start();                 // 5
echo s('foo,bar,baz')->select()->from(5)->shiftLeft(1)->start();   // 6
echo s('foo,bar,baz')->select()->from(5)->shiftLeft(-1)->start();  // 4

shiftRight($count): SubstringBuilderInterface

将结束索引从 $count 个字符处移动。 $count 可以是负数。

echo s('foo,bar,baz')->select()->to(5)->end();                  // 6
echo s('foo,bar,baz')->select()->to(5)->shiftRight(1)->end();   // 7
echo s('foo,bar,baz')->select()->to(5)->shiftRight(-1)->end();  // 5

shrink($count): SubstringBuilderInterface

将当前选择每边缩小 $count 个字符。

echo s('foo,bar,baz')->select()->fromFirst(',')->toNext(',')->shrink(1);  // bar

start(): int

返回当前起始索引。

echo s('foo,bar,baz')->select()->first('bar')->start();  // 4

to($index): SubstringBuilderInterface

将结束索引移动到索引 $index 的字符之后。

echo s('foo,bar')->select()->to(3);  // foo,

toLast($substring): SubstringBuilderInterface

将结束索引移动到最后一个出现 $substring 的最后一个字符之后。

echo s('foo,bar,baz')->select()->toLast(',');  // foo,bar,

toLength($length): SubstringBuilderInterface

将结束索引移动,使得选择的长度为 $length

echo s('foo,bar,baz')->select()->afterFirst(',')->toLength(3);  // bar

toNext($substring, $includeStart = false): SubstringBuilderInterface

将结束索引移动到最后一个出现 $substring 的第一个出现之后的最后一个字符之后。如果 $includeStarttrue,搜索从起始索引开始。否则,搜索从下一个字符开始。

echo s('foo,bar,foo,bar')->select()->toNext('bar');        // foo,bar
echo s('foo,bar,foo,bar')->select()->toNext('foo');        // foo,bar,foo
echo s('foo,bar,foo,bar')->select()->toNext('foo', true);  // foo

toRight($substring): SubstringBuilderInterface

将结束索引移动到字符串的末尾。

echo s('foo,bar')->select()->to(3)->toRight();  // foo,bar

toString(): string

以普通字符串返回所选子串。

echo s('foo,bar,baz')->select()->from(4)->to(6)->toString();  // bar

子串列表

CaseSensitiveBinarySubstringListCaseInsensitiveBinarySubstringListCaseSensitiveUnicodeSubstringListCaseInsensitiveUnicodeSubstringList 实现了与相应的 StringInterface 相同的方法。

本节描述了额外的方法和行为发生改变的方法。

afterSubstringAt($index): StringInterface

返回位于索引 $index 的子串之后的字符串(并在下一个子串之前)。

echo s('foo,bar;baz')->separate([',', ';'])->afterSubstringAt(0);  // ,
echo s('foo,bar;baz')->separate([',', ';'])->afterSubstringAt(1);  // ;
echo s('foo,bar;baz')->separate([',', ';'])->afterSubstringAt(2);  // <empty string>

beforeSubstringAt($index): StringInterface

返回位于索引 $index 的子字符串之前(以及前一个子字符串之后)的字符串。

echo s('foo,bar;baz')->separate([',', ';'])->beforeSubstringAt(0);  // <empty string>
echo s('foo,bar;baz')->separate([',', ';'])->beforeSubstringAt(1);  // ,
echo s('foo,bar;baz')->separate([',', ';'])->beforeSubstringAt(2);  // ;

convert($callable): array

convert 相同,但 $callable 接受一个包含当前子字符串信息的第二个参数。此附加参数是 SubstringInfo 的一个实例。

$lengths = s('foo,bar;baz')->separate([',', ';'])->convert(function ($s, $info) {
    return $info->length();
});   // $lengths = [3, 3, 3]

count(): int

返回子字符串的数量。您也可以使用 PHP 函数 count

echo s('foo,bar;baz')->separate([',', ';'])->count();  // 3
echo count(s('foo,bar;baz')->separate([',', ';']));    // 3

end(): array

返回每个子字符串后字符的索引。

$result = s('foo,bar;baz')->separate([',', ';'])->end();  // $result = [3, 7, 11]

getString(): StringInterface

返回原始字符串。

echo s('foo,bar;baz')->separate([',', ';'])->getString();  // foo,bar;baz

implode($separator): StringInterface

使用 $separator 连接子字符串。

echo s('foo,bar;baz')->separate([',', ';'])->implode('.');  // foo.bar.baz

info($template = null): array

返回每个子字符串的信息。如果 $templatenull,则返回的数组包含 SubstringInfo 的实例。如果提供模板,则返回的数组项将根据模板构建。

$info = s('foo,bar;baz')
    ->separate([',', ';'])
    ->info(['start' => SubstringListInterface::INFO_START, 'end' => SubstringListInterface::INFO_END]);
// $info = [['start' => 0, 'end' => 3], ['start' => 4, 'end' => 7], ['start' => 8, 'end' => 11]]

patch(): StringInterface

将子字符串更改应用到原始字符串。

echo s('foo,bar;baz')->separate([',', ';'])->reverse()->patch();  // oof,rab;zab

remove(): StringInterface

从原始字符串中删除子字符串。

echo s('foo,bar;baz')->separate([',', ';'])->remove();  // ,;

start(): array

返回每个子字符串第一个字符的索引。

$result = s('foo,bar;baz')->separate([',', ';'])->start();  // $result = [0, 4, 8]

substringAt($index): StringInterface

返回索引 $index 的子字符串。

echo s('foo,bar;baz')->separate([',', ';'])->substringAt(1);  // bar

toArray(): array

返回子字符串的数组。

transform($callable): SubstringListInterface

transform 相同,但 $callable 接受一个包含当前子字符串信息的第二个参数。此附加参数是 SubstringInfo 的一个实例。

echo s('foo,bar;baz')->separate([',', ';'])->transform(function ($s, $info) {
    return $info->index() . ': ' . $s;
})->implode(', ');   // 0: foo, 1: bar, 2: baz