Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

Stringy

> 编程语言
Open source

A PHP string manipulation library with multibyte support

2.4K stars0 likes2 views
WebsiteGitHub

About

A PHP string manipulation library with multibyte support

A PHP string manipulation library with multibyte support. Compatible with PHP 5.4+, PHP 7+, and HHVM.

php
s('string')->toTitleCase()->ensureRight('y') == 'Stringy'

Refer to the 1.x branch or 2.x branch for older documentation.

  • Why?
  • Installation
  • OO and Chaining
  • Implemented Interfaces
  • PHP 5.6 Creation
  • StaticStringy
  • Class methods
    • create
  • Instance methods
append at between camelize
chars collapseWhitespace contains containsAll
containsAny countSubstr dasherize delimit
endsWith endsWithAny ensureLeft ensureRight
first getEncoding hasLowerCase hasUpperCase
htmlDecode htmlEncode humanize indexOf
indexOfLast insert isAlpha isAlphanumeric
isBase64 isBlank isHexadecimal isJson
isLowerCase isSerialized isUpperCase last
length lines longestCommonPrefix longestCommonSuffix
longestCommonSubstring lowerCaseFirst pad padBoth
padLeft padRight prepend regexReplace
removeLeft removeRight repeat replace
reverse safeTruncate shuffle slugify
slice split startsWith startsWithAny
stripWhitespace substr surround swapCase
tidy titleize toAscii toBoolean
toLowerCase toSpaces toTabs toTitleCase
toUpperCase trim trimLeft trimRight
truncate underscored upperCamelize upperCaseFirst
  • Extensions
  • Tests
  • License

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!

php
// 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:

json
"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:

php
require 'vendor/autoload.php';

Otherwise, you can simply require the file directly:

php
require_once 'path/to/Stringy/src/Stringy.php';

And in either case, I'd suggest using an alias.

php
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:

php
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:

php
$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:

php
$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.

php
$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:

php
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.

php
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.

php
$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.

php
s('fòô')->append('bàř'); // 'fòôbàř'
at(int $index)

Returns the character at $index, with indexes starting at 0.

php
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.

php
s('{foo} and {bar}')->between('{', '}'); // 'foo'
camel

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPmultibytephpstringsutf-8

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言