Laraplus/String
This package provides a fluent easy-to-use interface for string manipulation. It integrates with Illuminate\Support
to enable a fluent syntax even when dealing with multiple results. All methods are UTF-8 friendly., (*1)
Installation
To install this package, simply require it using composer:, (*2)
composer require laraplus/string
Example usage
With this package you can avoid ugly nested str_* functions and never ending needle-haystack problems:, (*3)
str(' some text ')->trim()->substring(0, 4);
// instead of
substr(trim(' some text '), 0, 4);
If you have a slug "my-blog-title-4" and you need to find the index "4", you can simply write:, (*4)
$lastIndex = str($lastSlug)->explode('-')->last();
// instead of
$parts = $explode('-');
$lastIndex = array_pop($parts);
Lets say you have some custom "colon separated" multi line string that you need to parse:, (*5)
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
}
Full reference
Initialization
You can initialize the StringBuffer object directly or by using the str helper function:, (*6)
$string = new Laraplus\String\StringBuffer('Hello world!');
// or
$string = str('Hello world!');
Chaining
When the result of a method call is a string, it is automatically wrapped in a new StringBuffer instance, so that the
method calls can be chained., (*7)
// result: "HELLO"
str('hello world')->toUpper()->wordAt(0);
If you need to unwrap the object, you can do that by calling the get() method or simply cast it to string., (*8)
// a string "Hello world" is produced in all examples below
str('hello world')->ucfirst()->get();
(string)str('hello world')->ucfirst();
str('hello')->ucfirst() . ' world!';
When a method returns an array it is automatically wrapped in a Collection object, which enables further chaining:, (*9)
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)
});
For a full reference of available collection methods, see the Laravel documentation: http://laravel.com/docs/5.1/collections#available-methods, (*10)
Available methods
ucfirst()
Capitalize the first letter of the string., (*11)
// result: "Hello world"
str('hello world')->ucfirst();
lcfirst()
Lowercase the first letter of the string., (*12)
// result: "hello world"
str('Hello world')->lcfirst();
startsWith($needles)
Determine if the string starts with a given substring., (*13)
// returns true
str('Hello world')->startsWith('Hello');
// returns false
str('Hello world')->startsWith('world');
// returns true
str('Hello world')->startsWith(['H', 'W']);
endsWith($needles)
Determine if the string ends with a given substring., (*14)
// returns true
str('Hello world')->endsWith('world');
// returns false
str('Hello world')->endsWith('Hello');
// returns true
str('Hello world')->endsWith(['o', 'd']);
contains($needles)
Determine if the string contains a given substring., (*15)
// returns true
str('Hello world')->contains('world');
// returns false
str('Hello world')->contains('universe');
// returns true
str('Hello world')->contains(['w', 'u']);
equals($needles)
Determine if the string equals the given input in a constant time comparison., (*16)
// returns true
str('Hello world')->equals('Hello world');
// returns false
str('Hello world')->equals('Hello universe');
matches($pattern)
Determine if the string matches a given pattern., (*17)
// returns true
str('Hello/World')->matches('*/*');
// returns true
str('Hello world')->equals('Hello*');
explode($delimiters)
Split the string with given delimiter(s)., (*18)
// result: ['Hello', ' World']
str('Hello, World')->explode(',');
// result: ['one', 'two', 'three', 'four']
str('one:two,three:four')->explode([':', ',']);
indexOf($needle, $offset = 0)
Find the first occurrence of a given needle in the string, starting at the provided offset., (*19)
// returns 0
str('one, two')->indexOf('o');
// returns 7
str('one, two')->indexOf('o', 1);
lastIndexOf($needle, $offset = 0)
Find the last occurrence of a given needle in the string, starting at the provided offset., (*20)
// returns 7
str('one, two')->lastIndexOf('o');
// returns 0
str('one, two')->lastIndexOf('o', 1);
replace($search, $replace, &$count = 0)
Replace all occurrences of the search string with the replacement string., (*21)
// 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)
Returns the portion of string specified by the start and length parameters, (*22)
// result: 'world'
str('Hello world')->substring(6);
// result: 'll'
str('Hello world')->substring(2, 2);
toAscii()
Transliterate a UTF-8 value to ASCII., (*23)
// result: 'CcZzSs'
str('ČčŽžŠš')->toAscii();
toCamel()
Convert a value to camel case., (*24)
// result: 'helloWorld'
str('hello_world')->toCamel();
toSnake()
Convert a value to snake case., (*25)
// result: 'hello_world'
str('HelloWorld')->toSnake();
toStudly()
Convert a value to studly case., (*26)
// result: 'HelloWorld'
str('hello_world')->toStudly();
toTitle()
Convert a value to title case., (*27)
// result: 'Hello World'
str('hello world')->toTitle();
toSlug()
Convert a value to title case., (*28)
// result: 'hello-world'
str('Hello world')->toSlug();
toUpper()
Convert the given string to upper-case., (*29)
// result: 'HELLO WORLD'
str('Hello world')->toUpper();
toLower()
Convert the given string to lower-case., (*30)
// result: 'hello world'
str('Hello World')->toLower();
toSingular()
Get the singular form of an English word., (*31)
// result: 'person'
str('people')->toSingular();
toPlural()
Get the plural form of an English word., (*32)
// result: 'people'
str('person')->toPlural();
length()
Return the length of the given string., (*33)
// returns 11
str('Hello world')->length();
words($ignore = '?!;:,.')
Return a Collection of individual words in the string ignoring the given characters., (*34)
// result: ['one', 'two', 'three']
str('one, two, three')->words();
// result: ['one', 'two', 'three']
str('(one) : (two) : (three)')->words('(:)');
lines()
Return a collection of individual lines in the string., (*35)
// result: ['one', 'two', 'three']
str("one\ntwo\r\nthree")->lines();
prepend($string)
Prepend a given input to the string., (*36)
// result: 'hello world'
str('world')->prepend(' ')->prepend('hello');
append($string)
Append a given input to the string., (*37)
// result: 'hello world'
str('hello')->append(' ')->append('world');
trim($chars = null)
Trim given characters from both ends of the string. If no characters are provided, all white space is trimmed., (*38)
// result: 'hello world'
str(' hello world ')->trim();
// result: 'hello world'
str('--hello world--')->trim('-');
ltrim($chars = null)
Similar to trim(), but only trims characters from the left side., (*39)
// result: 'hello world '
str(' hello world ')->ltrim();
// result: 'hello world--'
str('--hello world--')->ltrim('-');
rtrim($chars = null)
Similar to trim(), but only trims characters from the right side., (*40)
// result: ' hello world'
str(' hello world ')->rtrim();
// result: '--hello world'
str('--hello world--')->rtrim('-');
limit($limit = 100, $end = '...')
Limit the number of characters in the string., (*41)
// result: 'hello...'
str('hello world')->limit(5);
// result: 'hello etc.'
str('hello world')->limit(5, ' etc.');
limitWords($limit = 100, $end = '...')
Limit the number of words in the string., (*42)
// 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)
Return the word at the given index., (*43)
// result: 'world'
str('Hello the world of PHP!')->wordAt(2);
tree($open = '{', $close = '}')
Parse a tree structure defined by the given delimiters., (*44)
//result: ['one', ['two', ['three'], 'four']]
str('one{two{three}four}')->tree();
Using offsets
Since the StringBuffer class implements the ArrayAccess interface, you can also use all of the usual offset goodies:, (*45)
$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'