lucleroy/php-strings

PHP library to manipulate strings.

0.1.0 2018-09-19 08:47 UTC

This package is not auto-updated.

Last update: 2024-05-24 12:23:00 UTC


README

PHP library to manipulate strings.

Table of contents

Introduction

This library provides an unified way to manage binary strings and Unicode strings.

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

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

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

You can work with case sentive or case insensitive strings.

use function LucLeroy\Strings\s;

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

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

In addition, it provides powerful methods for working with substrings.

use function LucLeroy\Strings\s;

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

Requirements

  • PHP 7.
  • mbstring extension.
  • intl extension.

Installation (with Composer)

Add the following to the require section of your composer.json file

"lucleroy/php-strings": "*"

and run composer update.

Usage

Basics

This library provides four main classes implementing StringInterface:

  • CaseSensitiveBinaryString to work with case sensitive binary strings.
  • CaseInsensitiveBinaryString to work with case insensitive binary strings.
  • CaseSensitiveUnicodeString to work with case sensitive Unicode strings.
  • CaseInsensitiveUnicodeString to work with case insensitive Unicode strings.

Important note: These classes are immutable.

Use the create method to create a string:

use LucLeroy\Strings\CaseSensitiveBinaryString;

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

By default, Unicode strings use an UTF-8 encoding. If you want to use another encoding you can specify it as a second arguments to create. You can use any encoding supporting by the mbstring extension (not necessary an Unicode encoding):

use LucLeroy\Strings\CaseSensitiveUnicodeString;

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

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

You can convert any type of string to any other type by using methods toCaseSensitive, toCaseInsensitive, toBinary, toUnicode.

Instead of using classes directly, you can use functions s for binary strings and u for Unicode strings. These functions are shortcuts to CaseSensitiveBinaryString:create and CaseSensitiveUnicodeString:create respectively.

Working with one substring

At first glance, it seems that this library does not provide methods for searching or extracting substrings. This is of course wrong. But the way to work with a substring is a bit peculiar.

To work with a substring, you must first call the select method which create a builder (immutable):

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

$builder = $str->select();

Then you use the builder methods to select a substring:

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

Then you can get information about the position of the substring with selection, start, end, length:

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

Note: The end of the selection is the first index after the selection.

You can also modify the substring with patch or remove it with remove:

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

You can extract the substring with build:

$substring = $builder->build();

echo $substring;  // World

As build returns an instance of the same type than the original string, you can then transform the substring:

$substring = $substring->upper();  

echo $substring;  // WORLD

Finally, you can reinject the modified substring into the original string with patch:

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

Of course, you can chain operations:

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

Working with multiple substrings

Some methods (explode, split, occurences, ...) return several substrings. The result is an instance of a class implementing SubstringListInterface which extends StringInterface, so you can use all the methods available for strings on the result of these methods:

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

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

Then use patch to patch the original string with the modified substrings:

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

If you don't care of the original string, you can retrieve the substrings as an array (of StringInterface) with toArray. You can also use implode to join the substrings into a single StringInterface.

Case transformers

If you want to transform a string to camel case, pascal case, ..., you must use the caseTransform. The argument of this method must implement CaseTransformerInterface (in namespace LucLeroy\Strings\CaseTransformer). Common transformers are available via the 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 keep only letter sequences and digit sequences and provides these sequences as an array of StringInterface. CaseTransformerInterface has a method transform which transform this array into a StringInterface.

To implement your own transformer, you can implement CaseTransformerInterface directly.

Most of the time, you can determine how to render a sequence based on the sequence itself and the two sequences next to it. For example, in camel case, the first sequence must be in lowercase and others in lowercase except for the first character which must be in uppercase. You can implement a case transformer depending only on the context by extending AbstractContextCaseTransformer. You must implement the transformPart method which has three arguments: the current part, the previous one, and the next one. A basic camel case transformer can be implemented as follows:

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

But there is even simpler: you can create a case transformer with the class SimpleCaseTransformer. You can rewrite the previous camel case transformer as follows:

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);

With SimpleCaseTransformer you can specify a different case for the first sequence and the others, and a different separator between diffrent types of sequences (letters or digits).

Reference

Strings

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

Returns a left-justified string of a given minimum size. The remaining space is filled with the string $fill;

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

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

Returns a right-justified string of a given minimum size. The remaining space is filled with the string $fill;

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

append($string): StringInterface

Adds $string to the end of the current string.

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

ascii(): UnicodeStringInterface

Available for Unicode strings only.

Converts the string to ASCII.

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

caseTransform($transformer): StringInterface

Converts the string to camel case, pascal case, kebab case, ...

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

Returns the character at the specified index as an ordinary string.

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

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

Returns a centered string of a given minimum size. The remaining space is filled with the string $fill;

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

chars(): string[]

Returns the characters composing the string as an array of ordinary strings.

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

clear(): StringInterface

Returns an empty string.

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

contains($substring): bool

Determines if $substring is a substring of the current string.

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

containsAll($substrings): bool

Determines if all the $substring are substrings of the current string.

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

containsAny($substrings): bool

Determines if any of the $substring i susbstring of the current string.

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

convert($callable)

Applies a custom tranformation to the string. The result can be anything.

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

countOf($substring): int

Returns the number of occurrences of $substring in the current string.

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

cut($cuts): SubstringListInterface

Returns a SubstringListInterface containing the current string cut to the specified positions.

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

endsWith($substring): bool

Determines if the current string ends with $substring.

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

endsWithAny($substrings): bool

Determines if the current string ends with any of $substrings.

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

ensureLeft($substring): StringInterface

If the current string does not start with $substring, adds $substring to the beginning of the current string.

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

ensureRight($substring): StringInterface

If the current string does not end with $substring, adds $substring to the end of the current string.

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

escapeControlChars(): StringInterface

Escapes control characters.

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

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

Splits the string by a delimiter.

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

Note: For a case insensitive string, all versions of the delimiter are replaced by the gicen version:

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

getEncoding(): string

Available for Unicode strings only.

Returns the encoding of the string.

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

is($string): bool

Determines is the string is equal to $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

Determines if the string is any of the $strings.

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

isAscii(): bool

Determines if the string contains only ASCII characters.

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

isEmpty(): bool

Determines if the string is empty.

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

isSubstringOf($string): bool

Determines if the string is a substring of $string.

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

isSubstringOfAll($strings): bool

Determines if the string is a substring of each of the strings in $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

Determines if the string is a substring of any of the strings in $strings.

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

length(): int

Returns the length of the string.

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

lines(): SubstringListInterface

Splits the string to lines. Supported EOL are: "\n", "\r\n", "\r".

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

lower(): StringInterface

Converts the string to lowercase.

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

lowerFirst(): StringInterface

Converts the first character of the string to lowercase.

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

occurences($substrings): SubstringListInterface

Returns all occurences of strings in $substrings.

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

patch(): StringInterface

Applies changes made to the substring to the parent string. If the string is not a substring, return $this.

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

prepend($string): StringInterface

Adds $string to the beginning of the current string.

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

repeat($multiplier = 2): StringInterface

Returns the string repeated $multiplier times.

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

repeatToSize($size): StringInterface

Repeats the string up to the given size.

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

replace($string): StringInterface

Replaces the current string with $string.

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

replaceAll($search, $replace): StringInterface

Replaces all occurrences of the $search string(s) with the $replace string(s). Works in the same way as PHP function str_replace.

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

reverse()

Reverses the characters of the string.

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

select($offset = 0): SubstringBuilder

Starts the selection of a substring, beginning at the given $offset.

separate($delimiters): SubstringListInterface

Splits the string by multiple delimiters.

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

shuffle(): StringInterface

Randomly shuffles the string.

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

split($size = 1): SubstringListInterface

Splits the string in substrings of $size characters.

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

squeeze($char = ' '): StringInterface

Replaces consecutive occurences of $char with one character only.

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

startsWith($substring): bool

Determines if the string starts with $substring.

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

startsWithAny($substrings): bool

Determines if the string starts with any of the strings in $substrings.

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

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

Adds $string1 to the beginning of the string and $string2 (or $string1 is $string2 is null) to the end.

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

titleize(): StringInterface

Converts first word of each word to uppercase, and the others to lowercase.

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

toString(): string

Converts the string to an ordinary string.

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

toBinary(): BinarfyStringInterface

Available for Unicode strings only.

Converts an Unicode string to a binary string.

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

toCaseSensitive(): CaseSensitiveInterface

Available for case insensitive strings only.

Converts a case insensitive string to a case sensitive string.

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

toCaseInsensitive(): CaseInsensitiveInterface

Available for case sensitive strings only.

Converts a case sensitive string to a case insensitive string.

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

toEncoding($encoding): UnicodeStringInterface

Available for Unicode strings only.

Modifies the encoding of the string.

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

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

Available for binary strings only.

Converts a binary string to an Unicode string with the specified $encoding.

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

transform($callable): StringInterface

Applies a custom tranformation to the string. The result must have the same type as the current string. If it is not true, it is converted.

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

trim($charlist = null): StringInterface

Strips whitespaces or characters in $charlist if not null from both the beginning an the end of the string.

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

trimLeft($charlist = null): StringInterface

Strips whitespaces or characters in $charlist if not null from the beginning of the string.

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

trimRight($charlist = null): StringInterface

Strips whitespaces or characters in $charlist if not null from the end of the string.

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

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

Truncates on the right to $size characters. If $string is not empty, deleted characters are replaced with it (additional characters are remove so that the length of the string does not exceed the given size).

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

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

Truncates on the left to $size characters. If $string is not empty, deleted characters are replaced with it (additional characters are remove so that the length of the string does not exceed the given size).

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

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

Truncates on the middle to $size characters. If $string is not empty, deleted characters are replaced with it (additional characters are remove so that the length of the string does not exceed the given size).

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

upper(): StringInterface

Converts the string to uppercase.

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

upperFirst(): StringInterface

Converts the first character of the string to upppercase.

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

Substring builder

To create a substring builder, use the select method on the string. The methods of the substring builder allow you to set a start index and a end index for the substring.

Note that:

  • The end index correspond to the index of the first excluded character.
  • If you provide an offset to the select method, indices are numbered from this offset. For example if the offset is 5, an index of 2 in the substring builder corresponds to an index of 7 in the string.

after($index): SubstringBuilderInterface

Moves the start index just after the index $index.

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

afterFirst($substring): SubstringBuilderInterface

Moves the start index just after the last character of the first occurence of $substring.

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

afterLast($substring): SubstringBuilderInterface

Moves the start index just after the last character of the last occurence of $substring.

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

at($index): SubstringBuilderInterface

Moves the start index and the end index to the index $index. The selection is empty. Useful to insert a string at a specific position.

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

atEndOfFirst($substring): SubstringBuilderInterface

Moves the start index and the end index just after the last character of the first occurence of $substring. The selection is empty. Useful to insert a string after a specific substring.

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

atEndOfLast($substring): SubstringBuilderInterface

Moves the start index and the end index just after the last character of the last occurence of $substring. The selection is empty. Useful to insert a string after a specific substring.

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

atStartOfFirst($substring): SubstringBuilderInterface

Moves the start index and the end index at the first character of the first occurence of $substring. The selection is empty. Useful to insert a string before a specific substring.

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

atStartOfLast($substring): SubstringBuilderInterface

Moves the start index and the end index at the first character of the last occurence of $substring. The selection is empty. Useful to insert a string before a specific substring.

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

before($index): SubstringBuilderInterface

Moves the end index to the specified index.

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

beforeLast($substring): SubstringBuilderInterface

Moves the end index to the first char of the last occurence of $substring.

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

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

Moves the end index to the first char of the first occurence of $substring from the current start index. If $includeStart is true, the search start at the start index. Otherwise, the search starts at the next character.

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

If $match is false, moves the start index and the end index so they select the first susbtring beginning with $open and finishing with $close.

If $match is true, moves the start index and the end index so they select the first susbtring beginning with $open and finishing with $close matching $open.

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

build(): StringInterface

Creates a StringInterface from the selection.

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

end(): int

Returns the end index of the selection.

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

first($substring): SubstringBuilderInterface

Selects the first occurrence of $substring.

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

from($index): SubstringBuilderInterface

Moves the start index to $index.

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

fromFirst($substring): SubstringBuilderInterface

Move the start index to the first character of the first occurence of $substring.

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

fromLast($substring): SubstringBuilderInterface

Moves the start index to the first character of the last occurence of $substring.

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

fromLeft(): SubstringBuilderInterface

Moves the start index to the beginning of the string.

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

fromLength($length): SubstringBuilderInterface

Moves the start index so that the selection length is $length.

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

grow($count): SubstringBuilderInterface

Expands the current selection by $count characters on each side.

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

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

If $match is false, moves the start index and the end index so they select the first susbtring preceded by $open and followed by $close.

If $match is true, moves the start index and the end index so they select the first susbtring preceded by $open and followed by $close matching $open.

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

isEmpty(): bool

Determines if the current selection is empty.

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

Selects the last occurrence of $substring.

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

length(): int

Returns the length of the selection.

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

longestCommonPrefix($string): SubstringBuilderInterface

Selects the longest string common to the current string and $string, starting from the beginning of each string.

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

longestCommonSubstring($string): SubstringBuilderInterface

Selects the longest string common to the current string and $string.

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

longestCommonSuffix($string): SubstringBuilderInterface

Selects the longest string common to the current string and $string, finishing at the end of each string.

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

patch($patch): StringInterface

Returns a StringInterface with the selection replaced by $patch.

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

remove(): StringInterface

Returns a StringInterface with the selection removed.

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

select($offset = 0): SubstringBuilderInterface

Start a new selection from the current selection. It is equivalent to do build followed by select.

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

selection(): array | null

If the selection is valid, returns an array containing the start index and the end index in this order. If the selection is invalid (for example if you try to select a substring which does not exist), returns null.

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

shiftLeft($count): SubstringBuilderInterface

Shifts the start index from $count characters. $count can be negative.

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

Shifts the end index from $count characters. $count can be negative.

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

Shrinks the current selection by $count characters on each side.

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

start(): int

Return the current start index.

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

to($index): SubstringBuilderInterface

Moves the end index just after the character at index $index.

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

toLast($substring): SubstringBuilderInterface

Moves the end index just after the last character of the last occurrence of $substring.

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

toLength($length): SubstringBuilderInterface

Moves the end index so that the selection length is $length.

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

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

Moves the end index just after the last character of the first occurrence of $substring from the start index. If $includeStart is true, the search start at the start index. Otherwise, the search starts at the next character.

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

Moves the end index to the end of the string.

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

toString(): string

Return the selected substring as an ordinary string.

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

Substring Lists

Classes CaseSensitiveBinarySubstringList, CaseInsensitiveBinarySubstringList, CaseSensitiveUnicodeSubstringList, CaseInsensitiveUnicodeSubstringList implements the same methods as the corresponding StringInterface.

This section describes additional methods and methods with an altered behavior.

afterSubstringAt($index): StringInterface

Returns the string just after the substring at index $index (and before the next substring).

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

Returns the string just before the substring at index $index (and after the previous substring).

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

Same as convert, but $callable accepts a second argument containing information about the current substring. This additional argument is an instance of SubstringInfo.

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

count(): int

Returns the number of substrings. You can also use the PHP function count.

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

end(): array

Returns indices of the character following each substring.

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

getString(): StringInterface

Returns the original string.

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

implode($separator): StringInterface

Join substrings with $separator.

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

info($template = null): array

Returns information about each substring. If $template is null, the returned array contains instances of SubstringInfo. If you provide a template, the returned array items are build according to the template.

$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

Applies substrings changes to the original string.

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

remove(): StringInterface

Remove substrings from the original string.

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

start(): array

Returns indices of the first character of each substring.

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

substringAt($index): StringInterface

Returns the substring at index $index.

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

toArray(): array

Returns an array of substrings.

transform($callable): SubstringListInterface

Same as transform, but $callable accepts a second argument containing information about the current substring. This additional argument is an instance of SubstringInfo.

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