PHP library to manipulate strings.
- Introduction
- Requirements
- Installation
- Usage
- Reference
- Strings
- alignLeft
- alignRight
- append
- ascii
- caseTransform
- charAt
- center
- chars
- clear
- contains
- containsAll
- containsAny
- convert
- countOf
- cut
- endsWith
- endsWithAny
- ensureLeft
- ensureRight
- escapeControlChars
- explode
- getEncoding
- is
- isAny
- isAscii
- isEmpty
- isSubstringOf
- isSubstringOfAll
- isSubstringOfAny
- length
- lines
- lower
- lowerFirst
- occurences
- patch
- prepend
- repeat
- repeatToSize
- replace
- replaceAll
- reverse
- select
- separate
- shuffle
- split
- squeeze
- startsWith
- startsWithAny
- surroundWith
- titleize
- toString
- toBinary
- toCaseSensitive
- toCaseInsensitive
- toEncoding
- toUnicode
- transform
- trim
- trimLeft
- trimRight
- truncate
- truncateLeft
- truncateMiddle
- upper
- upperFirst
- Substring builder
- after
- afterFirst
- afterLast
- at
- atEndOfFirst
- atEndOfLast
- atStartOfFirst
- atStartOfLast
- before
- beforeLast
- beforeNext
- betweenSubstrings
- build
- end
- first
- from
- fromFirst
- fromLast
- fromLeft
- fromLength
- grow
- insideSubstrings
- isEmpty
- last
- length
- longestCommonPrefix
- longestCommonSubstring
- longestCommonSuffix
- patch
- remove
- select
- selection
- shiftLeft
- shiftRight
- shrink
- start
- to
- toLast
- toLength
- toNext
- toRight
- toString
- Substring Lists
- Strings
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
- PHP 7.
- mbstring extension.
- intl extension.
Add the following to the require
section of your composer.json file
"lucleroy/php-strings": "*"
and run composer update
.
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.
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!
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
.
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).
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+-+-+'
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'
Adds $string
to the end of the current string.
echo s('Hello')->append(' World!'); // Hello World!
Available for Unicode strings only.
Converts the string to ASCII.
echo u('Доброе утро.')->ascii(); // Dobroe utro.
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
Returns the character at the specified index as an ordinary string.
echo s('Hello')->charAt(1); // 'e'
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+-+'
Returns the characters composing the string as an array of ordinary strings.
$chars = s('Hello')->chars; // $chars = ['H', 'e', 'l', 'l', 'o']
Returns an empty string.
echo s('Hello')->clear; // ''
Determines if $substring
is a substring of the current string.
echo s('Hello World!')->contains('Hello') ? 'true' : 'false'; // true
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
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
Applies a custom tranformation to the string. The result can be anything.
echo u('Доброе утро.')->convert(function ($s) {
return strlen($s);
}); // 22 (number)
Returns the number of occurrences of $substring
in the current string.
echo s('To be or not to be.')->countOf('be'); // 2
Returns a SubstringListInterface
containing the current string cut to the specified positions.
$result = s('Hello World!')->cut([5, 6, 11])->toString(); // $result = ['Hello', ' ', 'World', '!']
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
Determines if the current string ends with any of $substrings
.
echo s('Hello World!')->endsWithAny(['Everybody!', 'World!']) ? 'true' : 'false'; // true
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!
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!
Escapes control characters.
echo s("Hello\nWorld!")->escapeControlChars(); // Hello\nWorld!
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
Available for Unicode strings only.
Returns the encoding of the string.
echo u('Hello')->getEncoding(); // UTF-8
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
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
Determines if the string contains only ASCII characters.
echo u('Hello.')->isAscii() ? 'true' : 'false'; // true
echo u('Доброе утро.')->isAscii() ? 'true' : 'false'; // false
Determines if the string is empty.
echo s('Hello.')->isEmpty() ? 'true' : 'false'; // false
echo s('Hello.')->clear()->isEmpty() ? 'true' : 'false'; // true
Determines if the string is a substring of $string
.
echo s('Hello')->isSubstringOf('Hello World!') ? 'true' : 'false'; // true
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
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
Returns the length of the string.
echo s('Hello')->length(); // 5
Splits the string to lines. Supported EOL are: "\n", "\r\n", "\r".
$lines = s("Hello\nWorld!")->lines()->toString(); // $line s= ['Hello', 'World!']
Converts the string to lowercase.
echo s("HELLO")->lower(); // hello
Converts the first character of the string to lowercase.
echo s("HELLO")->lower(); // hELLO
Returns all occurences of strings in $substrings
.
echo s('Hello World!')->occurences(['o', 'l'])->implode(); // llool
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!
Adds $string
to the beginning of the current string.
echo s('World!')->prepend('Hello '); // 'Hello World!'
Returns the string repeated $multiplier
times.
echo s('+-')->repeat(5); // +-+-+-+-+-
Repeats the string up to the given size.
echo s('+-')->repeatToSize(15); // +-+-+-+-+-+-+-+
Replaces the current string with $string
.
echo s('Hello')->replace('Good Morning'); // Good Morning
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
Reverses the characters of the string.
echo s('Hello World!')->reverse(); // !dlroW olleH
Starts the selection of a substring, beginning at the given $offset
.
Splits the string by multiple delimiters.
echo s('123 456,789')->separate([' ', ','])->reverse()->patch(); // 321 654,987
Randomly shuffles the string.
echo s('Hello World!')->shuffle(); // rloodl!He lW
Splits the string in substrings of $size
characters.
echo s('Hello World!')->split(3)->implode('|'); // Hel|lo |Wor|ld!
Replaces consecutive occurences of $char
with one character only.
echo s('Hello World!')->squeeze(); // Hello World!
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
Determines if the string starts with any of the strings in $substrings
.
echo s('Hello World!')->startsWithAny(['Everybody!', 'World!']) ? 'true' : 'false'; // true
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!"
Converts first word of each word to uppercase, and the others to lowercase.
echo s('hELLO world!')->titleize(); // Hello World!
Converts the string to an ordinary string.
echo s('Hello World!')->toString(); // Hello World!
Available for Unicode strings only.
Converts an Unicode string to a binary string.
$str = u('Доброе утро.');
echo $str->length(); // 12
echo $str->toBinary()->length(); // 22
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
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
Available for Unicode strings only.
Modifies the encoding of the string.
echo u('«Hello World!»')->toEncoding('HTML'); // «Hello World!»
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
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
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!
Strips whitespaces or characters in $charlist
if not null
from the beginning of the string.
echo s('***Hello World!***')->trimLeft('*'); // Hello World!***
Strips whitespaces or characters in $charlist
if not null
from the end of the string.
echo s('***Hello World!***')->trimRight('*'); // ***Hello World!
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...
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!
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!
Converts the string to uppercase.
echo s("hello")->lower(); // HELLO
Converts the first character of the string to upppercase.
echo s("hello")->lower(); // Hello
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.
Moves the start index just after the index $index
.
echo s('foo,bar')->select()->after(3); // bar
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
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
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
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
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
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
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
Moves the end index to the specified index.
echo s('foo,bar')->select()->before(3); // foo
Moves the end index to the first char of the last occurence of $substring
.
echo s('foo,bar,foo')->select()->beforeLast('foo'); // foo,bar,
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>
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)
Creates a StringInterface
from the selection.
echo s('foo,bar,baz')->select()->first('bar')->build()->upper(); // BAR
Returns the end index of the selection.
echo s('foo,bar,baz')->select()->first('bar')->end(); // 7
Selects the first occurrence of $substring
.
echo s('foo,bar,foo,bar')->select()->first('bar')->patch('***'); // foo,***,foo,bar
Moves the start index to $index
.
echo s('foo,bar')->select()->from(3); // ,bar
Move the start index to the first character of the first occurence of $substring
.
echo s('foo,bar,baz')->select()->fromFirst(','); // ,bar,baz
Moves the start index to the first character of the last occurence of $substring
.
echo s('foo,bar,baz')->select()->fromLast(','); // ,baz
Moves the start index to the beginning of the string.
echo s('foo,bar')->select()->from(3)->fromLeft(); // foo,bar
Moves the start index so that the selection length is $length
.
echo s('foo,bar,baz')->select()->beforeLast(',')->fromLength(3); // bar
Expands the current selection by $count
characters on each side.
echo s('foo,bar,baz')->select()->afterFirst(',')->beforeNext(',')->grow(1); // ,bar,
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
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
Selects the last occurrence of $substring
.
echo s('foo,bar,foo,bar')->select()->last('bar')->patch('***'); // foo,bar,foo,***
Returns the length of the selection.
echo s('foo,bar,baz')->select()->first('bar')->length(); // 3
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
Selects the longest string common to the current string and $string
.
echo s('foo,bar,baz')->select()->longestCommonSubstring('bar,baz,foo'); // bar,baz
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
Returns a StringInterface
with the selection replaced by $patch
.
echo s('foo,bar,baz')->select()->first('bar')->patch('***'); // foo,***,baz
Returns a StringInterface
with the selection removed.
echo s('foo,bar,baz')->select()->first('bar')->remove(''); // foo,,baz
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
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]
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
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
Shrinks the current selection by $count
characters on each side.
echo s('foo,bar,baz')->select()->fromFirst(',')->toNext(',')->shrink(1); // bar
Return the current start index.
echo s('foo,bar,baz')->select()->first('bar')->start(); // 4
Moves the end index just after the character at index $index
.
echo s('foo,bar')->select()->to(3); // foo,
Moves the end index just after the last character of the last occurrence of $substring
.
echo s('foo,bar,baz')->select()->toLast(','); // foo,bar,
Moves the end index so that the selection length is $length
.
echo s('foo,bar,baz')->select()->afterFirst(',')->toLength(3); // bar
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
Moves the end index to the end of the string.
echo s('foo,bar')->select()->to(3)->toRight(); // foo,bar
Return the selected substring as an ordinary string.
echo s('foo,bar,baz')->select()->from(4)->to(6)->toString(); // bar
Classes CaseSensitiveBinarySubstringList
, CaseInsensitiveBinarySubstringList
,
CaseSensitiveUnicodeSubstringList
, CaseInsensitiveUnicodeSubstringList
implements the same methods as the corresponding
StringInterface
.
This section describes additional methods and methods with an altered behavior.
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>
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); // ;
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]
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
Returns indices of the character following each substring.
$result = s('foo,bar;baz')->separate([',', ';'])->end(); // $result = [3, 7, 11]
Returns the original string.
echo s('foo,bar;baz')->separate([',', ';'])->getString(); // foo,bar;baz
Join substrings with $separator
.
echo s('foo,bar;baz')->separate([',', ';'])->implode('.'); // foo.bar.baz
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]]
Applies substrings changes to the original string.
echo s('foo,bar;baz')->separate([',', ';'])->reverse()->patch(); // oof,rab;zab
Remove substrings from the original string.
echo s('foo,bar;baz')->separate([',', ';'])->remove(); // ,;
Returns indices of the first character of each substring.
$result = s('foo,bar;baz')->separate([',', ';'])->start(); // $result = [0, 4, 8]
Returns the substring at index $index
.
echo s('foo,bar;baz')->separate([',', ';'])->substringAt(1); // bar
Returns an array of substrings.
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