
A PHP string manipulation library with multibyte support. Compatible with PHP
5.4+, PHP 7+, and HHVM.
s('string')->toTitleCase()->ensureRight('y') == 'Stringy'
Refer to the 1.x branch or
2.x branch for older
documentation.

Why?
In part due to a lack of multibyte support (including UTF-8) across many of
PHP's standard string functions. But also to offer an OO wrapper around the
mbstring module's multibyte-compatible functions. Stringy handles some quirks,
provides additional functionality, and hopefully makes strings a little easier
to work with!
// Standard library
strtoupper('fòôbàř'); // 'FòôBàř'
strlen('fòôbàř'); // 10
// mbstring
mb_strtoupper('fòôbàř'); // 'FÒÔBÀŘ'
mb_strlen('fòôbàř'); // '6'
// Stringy
s('fòôbàř')->toUpperCase(); // 'FÒÔBÀŘ'
s('fòôbàř')->length(); // '6'
Installation
If you're using Composer to manage dependencies, you can include the following
in your composer.json file:
"require": {
"danielstjules/stringy": "~3.1.0"
}
Then, after running composer update or php composer.phar update, you can
load the class using Composer's autoloading:
require 'vendor/autoload.php';
Otherwise, you can simply require the file directly:
require_once 'path/to/Stringy/src/Stringy.php';
And in either case, I'd suggest using an alias.
use Stringy\Stringy as S;
Please note that Stringy relies on the mbstring module for its underlying
multibyte support. If the module is not found, Stringy will use
symfony/polyfill-mbstring.
ex-mbstring is a non-default, but very common module. For example, with debian
and ubuntu, it's included in libapache2-mod-php5, php5-cli, and php5-fpm. For
OSX users, it's a default for any version of PHP installed with homebrew.
If compiling PHP from scratch, it can be included with the
--enable-mbstring flag.
OO and Chaining
The library offers OO method chaining, as seen below:
use Stringy\Stringy as S;
echo S::create('fòô bàř')->collapseWhitespace()->swapCase(); // 'FÒÔ BÀŘ'
Stringy\Stringy has a __toString() method, which returns the current string
when the object is used in a string context, ie:
(string) S::create('foo') // 'foo'
Implemented Interfaces
Stringy\Stringy implements the IteratorAggregate interface, meaning that
foreach can be used with an instance of the class:
$stringy = S::create('fòôbàř');
foreach ($stringy as $char) {
echo $char;
}
// 'fòôbàř'
It implements the Countable interface, enabling the use of count() to
retrieve the number of characters in the string:
$stringy = S::create('fòô');
count($stringy); // 3
Furthermore, the ArrayAccess interface has been implemented. As a result,
isset() can be used to check if a character at a specific index exists. And
since Stringy\Stringy is immutable, any call to offsetSet or offsetUnset
will throw an exception. offsetGet has been implemented, however, and accepts
both positive and negative indexes. Invalid indexes result in an
OutOfBoundsException.
$stringy = S::create('bàř');
echo $stringy[2]; // 'ř'
echo $stringy[-2]; // 'à'
isset($stringy[-4]); // false
$stringy[3]; // OutOfBoundsException
$stringy[2] = 'a'; // Exception
PHP 5.6 Creation
As of PHP 5.6, use function is
available for importing functions. Stringy exposes a namespaced function,
Stringy\create, which emits the same behaviour as Stringy\Stringy::create().
If running PHP 5.6, or another runtime that supports the use function syntax,
you can take advantage of an even simpler API as seen below:
use function Stringy\create as s;
// Instead of: S::create('fòô bàř')
s('fòô bàř')->collapseWhitespace()->swapCase();
StaticStringy
All methods listed under "Instance methods" are available as part of a static
wrapper. For StaticStringy methods, the optional encoding is expected to be the
last argument. The return value is not cast, and may thus be of type Stringy,
integer, boolean, etc.
use Stringy\StaticStringy as S;
// Translates to Stringy::create('fòôbàř')->slice(0, 3);
// Returns a Stringy object with the string "fòô"
S::slice('fòôbàř', 0, 3);
Class methods
create(mixed $str [, $encoding ])
Creates a Stringy object and assigns both str and encoding properties
the supplied values. $str is cast to a string prior to assignment, and if
$encoding is not specified, it defaults to mb_internal_encoding(). It
then returns the initialized object. Throws an InvalidArgumentException
if the first argument is an array or object without a __toString method.
$stringy = S::create('fòôbàř'); // 'fòôbàř'
Instance Methods
Stringy objects are immutable. All examples below make use of PHP 5.6
function importing, and PHP 5.4 short array syntax. They also assume the
encoding returned by mb_internal_encoding() is UTF-8. For further details,
see the documentation for the create method above, as well as the notes
on PHP 5.6 creation.
append(string $string)
Returns a new string with $string appended.
s('fòô')->append('bàř'); // 'fòôbàř'
at(int $index)
Returns the character at $index, with indexes starting at 0.
s('fòôbàř')->at(3); // 'b'
between(string $start, string $end [, int $offset])
Returns the substring between $start and $end, if found, or an empty
string. An optional offset may be supplied from which to begin the
search for the start string.
s('{foo} and {bar}')->between('{', '}'); // 'foo'
camelize()
Returns a camelCase version of the string. Trims surrounding spaces,
capitalizes letters following digits, spaces, dashes and underscores,
and removes spaces, dashes, as well as underscores.
s('Camel-Case')->camelize(); // 'camelCase'
chars()
Returns an array consisting of the characters in the string.
s('fòôbàř')->chars(); // ['f', 'ò', 'ô', 'b', 'à', 'ř']
collapseWhitespace()
Trims the string and replaces consecutive whitespace characters with a
single space. This includes tabs and newline characters, as well as
multibyte whitespace such as the thin space and ideographic space.
s(' Ο συγγραφέας ')->collapseWhitespace(); // 'Ο συγγραφέας'
contains(string $needle [, boolean $caseSensitive = true ])
Returns true if the string contains $needle, false otherwise. By default,
the comparison is case-sensitive, but can be made insensitive
by setting $caseSensitive to false.
s('Ο συγγραφέας είπε')->contains('συγγραφέας'); // true
containsAll(array $needles [, boolean $caseSensitive = true ])
Returns true if the string contains all $needles, false otherwise. By
default the comparison is case-sensitive, but can be made insensitive by
setting $caseSensitive to false.
s('foo & bar')->containsAll(['foo', 'bar']); // true
containsAny(array $needles [, boolean $caseSensitive = true ])
Returns true if the string contains any $needles, false otherwise. By
default the comparison is case-sensitive, but can be made insensitive by
setting $caseSensitive to false.
s('str contains foo')->containsAny(['foo', 'bar']); // true
countSubstr(string $substring [, boolean $caseSensitive = true ])
Returns the number of occurrences of $substring in the given string.
By default, the comparison is case-sensitive, but can be made insensitive
by setting $caseSensitive to false.
s('Ο συγγραφέας είπε')->countSubstr('α'); // 2