PHPackages                             voku/stringy - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. voku/stringy

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

voku/stringy
============

A string manipulation library with multibyte support

7.0.1(1mo ago)1793.9M↓37.3%24[1 PRs](https://github.com/voku/Stringy/pulls)16MITPHPPHP &gt;=7.1.0CI passing

Since Jul 29Pushed 3w ago6 watchersCompare

[ Source](https://github.com/voku/Stringy)[ Packagist](https://packagist.org/packages/voku/stringy)[ Docs](https://github.com/danielstjules/Stringy)[ Fund](https://www.paypal.me/moelleken)[ GitHub Sponsors](https://github.com/voku)[ RSS](/packages/voku-stringy/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (17)Versions (112)Used By (16)

[![SWUbanner](https://raw.githubusercontent.com/vshymanskyy/StandWithUkraine/main/banner2-direct.svg)](https://github.com/vshymanskyy/StandWithUkraine/blob/main/docs/README.md)

[![Build Status](https://github.com/voku/Stringy/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/voku/Stringy/actions)[![codecov.io](https://camo.githubusercontent.com/2b5e03b4f93b8b323af1f7d91641a23f85342197a6781c5913520e8008b7a94b/68747470733a2f2f636f6465636f762e696f2f6769746875622f766f6b752f537472696e67792f636f7665726167652e7376673f6272616e63683d6d6173746572)](https://codecov.io/github/voku/Stringy?branch=master)[![Codacy Badge](https://camo.githubusercontent.com/90f891bf8761184a72364def8b5abd659085404b9dc274e2c7fccbe4db3f41df/68747470733a2f2f6170692e636f646163792e636f6d2f70726f6a6563742f62616467652f67726164652f3937633436343637653538353436376438383462616331313330636234356535)](https://www.codacy.com/app/voku/Stringy)[![Latest Stable Version](https://camo.githubusercontent.com/f6ce73259fa462b346a571f365223b9e76cd12826414a3fe319ad91fe462fc4b/68747470733a2f2f706f7365722e707567782e6f72672f766f6b752f737472696e67792f762f737461626c65)](https://packagist.org/packages/voku/stringy)[![Total Downloads](https://camo.githubusercontent.com/a7f461f560b8d0c8bd022b539db32b3d42a44f16a801254c44e07c98dbb9ed5b/68747470733a2f2f706f7365722e707567782e6f72672f766f6b752f737472696e67792f646f776e6c6f616473)](https://packagist.org/packages/voku/stringy)[![License](https://camo.githubusercontent.com/9716256121a893ef24a8abea061e5f126e4e26d5ebad3d66e82ed8b23ec6ec3f/68747470733a2f2f706f7365722e707567782e6f72672f766f6b752f737472696e67792f6c6963656e7365)](https://packagist.org/packages/voku/stringy)[![Donate to this project using Paypal](https://camo.githubusercontent.com/0d6e4d8b50b5983a58205941b1a581b1305903393b7a39da574e3f60af3c7f5b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f70617970616c2d646f6e6174652d79656c6c6f772e737667)](https://www.paypal.me/moelleken)[![Donate to this project using Patreon](https://camo.githubusercontent.com/f9e075baad95563481d35174d43ef50757281abb6bc795d0f473fad452afa030/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f70617472656f6e2d646f6e6174652d79656c6c6f772e737667)](https://www.patreon.com/voku)

🉑 Stringy
---------

[](#accept-stringy)

A PHP string manipulation library with multibyte support. Compatible with PHP 7+

100% compatible with the original "[Stringy](https://github.com/danielstjules/Stringy)" library, but this fork is optimized for performance and is using PHP 7+ features.

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

- [Why?](#why)
- [Alternative](#alternative)
- [Installation](#installation-via-composer-require)
- [OO and Chaining](#oo-and-chaining)
- [Implemented Interfaces](#implemented-interfaces)
- [PHP Class Call Creation](#php-class-call-creation)
- [Class methods](#class-methods)
    - [create](#createmixed-str--encoding-)
- [Instance methods](#instance-methods)
- [Extensions](#extensions)
- [Tests](#tests)
- [License](#license)

Why?
----

[](#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
$stringy = Stringy\Stringy::create('fòôbàř');
$stringy->toUpperCase();    // 'FÒÔBÀŘ'
$stringy->length();         // '6'
```

Alternative
-----------

[](#alternative)

If you like a more Functional Way to edit strings, then you can take a look at [voku/portable-utf8](https://github.com/voku/portable-utf8), also "voku/Stringy" used the functions from the "Portable UTF-8"-Class but in a more Object Oriented Way.

```
// Portable UTF-8
use voku\helper\UTF8;
UTF8::strtoupper('fòôbàř');    // 'FÒÔBÀŘ'
UTF8::strlen('fòôbàř');        // '6'
```

Installation via "composer require"
-----------------------------------

[](#installation-via-composer-require)

```
composer require voku/stringy
```

Installation via composer (manually)
------------------------------------

[](#installation-via-composer-manually)

If you're using Composer to manage dependencies, you can include the following in your composer.json file:

```
"require": {
    "voku/stringy": "~6.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;
```

OO and Chaining
---------------

[](#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
----------------------

[](#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 Class Call Creation
-----------------------

[](#php-class-call-creation)

As of PHP 5.6+, [`use function`](https://wiki.php.net/rfc/use_function) is available for importing functions. Stringy exposes a namespaced function, `Stringy\create`, which emits the same behaviour as `Stringy\Stringy::create()`.

```
use function Stringy\create as s;

// Instead of: S::create('fòô     bàř')
s('fòô     bàř')->collapseWhitespace()->swapCase();
```

Class methods
-------------

[](#class-methods)

##### create(mixed $str \[, $encoding \])

[](#createmixed-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àř', 'UTF-8'); // 'fòôbàř'
```

If you need a collection of Stringy objects you can use the S::collection() method.

```
$stringyCollection = \Stringy\collection(['fòôbàř', 'lall', 'öäü']);
```

Instance Methods
----------------

[](#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.

[after](#afterstring-string-static)[afterFirst](#afterfirststring-separator-static)[afterFirstIgnoreCase](#afterfirstignorecasestring-separator-static)[afterLast](#afterlaststring-separator-static)[afterLastIgnoreCase](#afterlastignorecasestring-separator-static)[append](#appendstring-suffix-static)[appendPassword](#appendpasswordint-length-static)[appendRandomString](#appendrandomstringint-length-string-possiblechars-static)[appendStringy](#appendstringycollectionstringystatic-suffix-static)[appendUniqueIdentifier](#appenduniqueidentifierintstring-entropyextra-bool-md5-static)[at](#atint-index-static)[base64Decode](#base64decode-self)[base64Encode](#base64encode-self)[bcrypt](#bcryptintstring-options-static)[before](#beforestring-string-static)[beforeFirst](#beforefirststring-separator-static)[beforeFirstIgnoreCase](#beforefirstignorecasestring-separator-static)[beforeLast](#beforelaststring-separator-static)[beforeLastIgnoreCase](#beforelastignorecasestring-separator-static)[between](#betweenstring-start-string-end-int-offset-static)[callUserFunction](#calluserfunctioncallable-function-mixed-parameter-static)[camelize](#camelize-static)[capitalizePersonalName](#capitalizepersonalname-static)[chars](#chars-string)[chunk](#chunkint-length-static)[chunkCollection](#chunkcollectionint-length-collectionstringystatic)[collapseWhitespace](#collapsewhitespace-static)[contains](#containsstring-needle-bool-casesensitive-bool)[containsAll](#containsallstring-needles-bool-casesensitive-bool)[containsAny](#containsanystring-needles-bool-casesensitive-bool)[containsBom](#containsbom-bool)[count](#count-int)[countSubstr](#countsubstrstring-substring-bool-casesensitive-int)[crc32](#crc32-int)[create](#createmixed-str-string-encoding-static)[crypt](#cryptstring-salt-static)[dasherize](#dasherize-static)[decrypt](#decryptstring-password-static)[delimit](#delimitstring-delimiter-static)[encode](#encodestring-new_encoding-bool-auto_detect_encoding-static)[encrypt](#encryptstring-password-static)[endsWith](#endswithstring-substring-bool-casesensitive-bool)[endsWithAny](#endswithanystring-substrings-bool-casesensitive-bool)[ensureLeft](#ensureleftstring-substring-static)[ensureRight](#ensurerightstring-substring-static)[escape](#escape-static)[explode](#explodestring-delimiter-int-limit-arrayintstatic)[explodeCollection](#explodecollectionstring-delimiter-int-limit-collectionstringystatic)[extractIntegers](#extractintegers-static)[extractSpecialCharacters](#extractspecialcharacters-static)[extractText](#extracttextstring-search-intnull-length-string-replacerforskippedtext-static)[first](#firstint-n-static)[format](#formatmixed-args-static)[getEncoding](#getencoding-string)[getIterator](#getiterator-arrayiterator)[hardWrap](#hardwrapint-width-string-break-static)[hasLowerCase](#haslowercase-bool)[hasUpperCase](#hasuppercase-bool)[hash](#hashstring-algorithm-static)[hexDecode](#hexdecode-static)[hexEncode](#hexencode-static)[htmlDecode](#htmldecodeint-flags-static)[htmlEncode](#htmlencodeint-flags-static)[humanize](#humanize-static)[in](#instring-str-bool-casesensitive-bool)[indexOf](#indexofstring-needle-int-offset-falseint)[indexOfIgnoreCase](#indexofignorecasestring-needle-int-offset-falseint)[indexOfLast](#indexoflaststring-needle-int-offset-falseint)[indexOfLastIgnoreCase](#indexoflastignorecasestring-needle-int-offset-falseint)[insert](#insertstring-substring-int-index-static)[is](#isstring-pattern-bool)[isAlpha](#isalpha-bool)[isAlphanumeric](#isalphanumeric-bool)[isAscii](#isascii-bool)[isBase64](#isbase64bool-emptystringisvalid-bool)[isBinary](#isbinary-bool)[isBlank](#isblank-bool)[isBom](#isbom-bool)[isEmail](#isemailbool-useexampledomaincheck-bool-usetypoindomaincheck-bool-usetemporarydomaincheck-bool-usednscheck-bool)[isEmpty](#isempty-bool)[isEquals](#isequalsstringstringy-str-bool)[isEqualsCaseInsensitive](#isequalscaseinsensitivefloatintstringstringy-str-bool)[isEqualsCaseSensitive](#isequalscasesensitivefloatintstringstringy-str-bool)[isHexadecimal](#ishexadecimal-bool)[isHtml](#ishtml-bool)[isJson](#isjsonbool-onlyarrayorobjectresultsarevalid-bool)[isLowerCase](#islowercase-bool)[isNotEmpty](#isnotempty-bool)[isNumeric](#isnumeric-bool)[isPrintable](#isprintable-bool)[isPunctuation](#ispunctuation-bool)[isSerialized](#isserialized-bool)[isSimilar](#issimilarstring-str-float-minpercentforsimilarity-bool)[isUpperCase](#isuppercase-bool)[isUrl](#isurlbool-disallow_localhost-bool)[isUtf8](#isutf8bool-strict-bool)[isUtf16](#isutf16-falseint)[isUtf32](#isutf32-falseint)[isWhitespace](#iswhitespace-bool)[jsonSerialize](#jsonserialize-string)[kebabCase](#kebabcase-static)[last](#lastint-n-static)[lastSubstringOf](#lastsubstringofstring-needle-bool-beforeneedle-static)[lastSubstringOfIgnoreCase](#lastsubstringofignorecasestring-needle-bool-beforeneedle-static)[length](#length-int)[lineWrap](#linewrapint-limit-string-break-bool-add_final_break-stringnull-delimiter-static)[lineWrapAfterWord](#linewrapafterwordint-limit-string-break-bool-add_final_break-stringnull-delimiter-static)[lines](#lines-static)[linesCollection](#linescollection-collectionstringystatic)[longestCommonPrefix](#longestcommonprefixstring-otherstr-static)[longestCommonSubstring](#longestcommonsubstringstring-otherstr-static)[longestCommonSuffix](#longestcommonsuffixstring-otherstr-static)[lowerCaseFirst](#lowercasefirst-static)[matchCaseInsensitive](#matchcaseinsensitivestringstringy-str-bool)[matchCaseSensitive](#matchcasesensitivestringstringy-str-bool)[md5](#md5-static)[newLineToHtmlBreak](#newlinetohtmlbreak-static)[nth](#nthint-step-int-offset-static)[offsetExists](#offsetexistsint-offset-bool)[offsetGet](#offsetgetint-offset-string)[offsetSet](#offsetsetint-offset-mixed-value-void)[offsetUnset](#offsetunsetint-offset-void)[pad](#padint-length-string-padstr-string-padtype-static)[padBoth](#padbothint-length-string-padstr-static)[padLeft](#padleftint-length-string-padstr-static)[padRight](#padrightint-length-string-padstr-static)[pascalCase](#pascalcase-static)[prepend](#prependstring-prefix-static)[prependStringy](#prependstringycollectionstringystatic-prefix-static)[regexReplace](#regexreplacestring-pattern-string-replacement-string-options-string-delimiter-static)[removeHtml](#removehtmlstring-allowabletags-static)[removeHtmlBreak](#removehtmlbreakstring-replacement-static)[removeLeft](#removeleftstring-substring-static)[removeRight](#removerightstring-substring-static)[removeXss](#removexss-static)[repeat](#repeatint-multiplier-static)[replace](#replacestring-search-string-replacement-bool-casesensitive-static)[replaceAll](#replaceallstring-search-stringstring-replacement-bool-casesensitive-static)[replaceBeginning](#replacebeginningstring-search-string-replacement-static)[replaceEnding](#replaceendingstring-search-string-replacement-static)[replaceFirst](#replacefirststring-search-string-replacement-static)[replaceLast](#replacelaststring-search-string-replacement-static)[reverse](#reverse-static)[safeTruncate](#safetruncateint-length-string-substring-bool-ignoredonotsplitwordsforoneword-static)[setInternalEncoding](#setinternalencodingstring-new_encoding-static)[sha1](#sha1-static)[sha256](#sha256-static)[sha512](#sha512-static)[shortenAfterWord](#shortenafterwordint-length-string-straddon-static)[shuffle](#shuffle-static)[similarity](#similaritystring-str-float)[slice](#sliceint-start-int-end-static)[slugify](#slugifystring-separator-string-language-string-replacements-bool-replace_extra_symbols-bool-use_str_to_lower-bool-use_transliterate-static)[snakeCase](#snakecase-static)[snakeize](#snakeize-static)[softWrap](#softwrapint-width-string-break-static)[split](#splitstring-pattern-int-limit-static)[splitCollection](#splitcollectionstring-pattern-int-limit-collectionstringystatic)[startsWith](#startswithstring-substring-bool-casesensitive-bool)[startsWithAny](#startswithanystring-substrings-bool-casesensitive-bool)[strip](#stripstringstring-search-static)[stripWhitespace](#stripwhitespace-static)[stripeCssMediaQueries](#stripecssmediaqueries-static)[stripeEmptyHtmlTags](#stripeemptyhtmltags-static)[studlyCase](#studlycase-static)[substr](#substrint-start-int-length-static)[substring](#substringint-start-int-length-static)[substringOf](#substringofstring-needle-bool-beforeneedle-static)[substringOfIgnoreCase](#substringofignorecasestring-needle-bool-beforeneedle-static)[surround](#surroundstring-substring-static)[swapCase](#swapcase-static)[tidy](#tidy-static)[titleize](#titleizestringnull-ignore-stringnull-word_define_chars-stringnull-language-static)[titleizeForHumans](#titleizeforhumansstring-ignore-static)[toAscii](#toasciistring-language-bool-removeunsupported-static)[toBoolean](#toboolean-bool)[toLowerCase](#tolowercasebool-trytokeepstringlength-stringnull-lang-static)[toSpaces](#tospacesint-tablength-static)[toString](#tostring-string)[toTabs](#totabsint-tablength-static)[toTitleCase](#totitlecase-static)[toTransliterate](#totransliteratebool-strict-string-unknown-static)[toUpperCase](#touppercasebool-trytokeepstringlength-stringnull-lang-static)[trim](#trimstring-chars-static)[trimLeft](#trimleftstring-chars-static)[trimRight](#trimrightstring-chars-static)[truncate](#truncateint-length-string-substring-static)[underscored](#underscored-static)[upperCamelize](#uppercamelize-static)[upperCaseFirst](#uppercasefirst-static)[urlDecode](#urldecode-static)[urlDecodeMulti](#urldecodemulti-static)[urlDecodeRaw](#urldecoderaw-static)[urlDecodeRawMulti](#urldecoderawmulti-static)[urlEncode](#urlencode-static)[urlEncodeRaw](#urlencoderaw-static)[urlify](#urlifystring-separator-string-language-string-replacements-bool-strtolower-static)[utf8ify](#utf8ify-static)[words](#wordsstring-char_list-bool-remove_empty_values-intnull-remove_short_values-static)[wordsCollection](#wordscollectionstring-char_list-bool-remove_empty_values-intnull-remove_short_values-collectionstringystatic)[wrap](#wrapstring-substring-static)after(string $string): static
-----------------------------

[](#afterstring-string-static)

[↑](#voku-php-readme-class-methods)Return part of the string occurring after a specific string.

EXAMPLE: `s('宮本 茂')->after('本'); // ' 茂'`

**Parameters:**

- `string $string The delimiting string.`

**Return:**

- `static`

---

afterFirst(string $separator): static
-------------------------------------

[](#afterfirststring-separator-static)

[↑](#voku-php-readme-class-methods)Gets the substring after the first occurrence of a separator.

If no match is found returns new empty Stringy object.

EXAMPLE: `s('')->afterFirst('b'); // '>'`

**Parameters:**

- `string $separator`

**Return:**

- `static`

---

afterFirstIgnoreCase(string $separator): static
-----------------------------------------------

[](#afterfirstignorecasestring-separator-static)

[↑](#voku-php-readme-class-methods)Gets the substring after the first occurrence of a separator.

If no match is found returns new empty Stringy object.

EXAMPLE: `s('')->afterFirstIgnoreCase('b'); // '>'`

**Parameters:**

- `string $separator`

**Return:**

- `static`

---

afterLast(string $separator): static
------------------------------------

[](#afterlaststring-separator-static)

[↑](#voku-php-readme-class-methods)Gets the substring after the last occurrence of a separator.

If no match is found returns new empty Stringy object.

EXAMPLE: `s('')->afterLast('b'); // '>'`

**Parameters:**

- `string $separator`

**Return:**

- `static`

---

afterLastIgnoreCase(string $separator): static
----------------------------------------------

[](#afterlastignorecasestring-separator-static)

[↑](#voku-php-readme-class-methods)Gets the substring after the last occurrence of a separator.

If no match is found returns new empty Stringy object.

EXAMPLE: `s('')->afterLastIgnoreCase('b'); // '>'`

**Parameters:**

- `string $separator`

**Return:**

- `static`

---

append(string $suffix): static
------------------------------

[](#appendstring-suffix-static)

[↑](#voku-php-readme-class-methods)Returns a new string with $suffix appended.

EXAMPLE: `s('fòô')->append('bàř'); // 'fòôbàř'`

**Parameters:**

- `string ...$suffix The string to append.`

**Return:**

- `static Object with appended $suffix.`

---

appendPassword(int $length): static
-----------------------------------

[](#appendpasswordint-length-static)

[↑](#voku-php-readme-class-methods)Append an password (limited to chars that are good readable).

EXAMPLE: `s('')->appendPassword(8); // e.g.: '89bcdfgh'`

**Parameters:**

- `int $length Length of the random string.`

**Return:**

- `static Object with appended password.`

---

appendRandomString(int $length, string $possibleChars): static
--------------------------------------------------------------

[](#appendrandomstringint-length-string-possiblechars-static)

[↑](#voku-php-readme-class-methods)Append an random string.

EXAMPLE: `s('')->appendUniqueIdentifier(5, 'ABCDEFGHI'); // e.g.: 'CDEHI'`

**Parameters:**

- `int $length Length of the random string.`
- `string $possibleChars [optional] Characters string for the random selection.`

**Return:**

- `static Object with appended random string.`

---

appendStringy(\\CollectionStringy|static $suffix): static
---------------------------------------------------------

[](#appendstringycollectionstringystatic-suffix-static)

[↑](#voku-php-readme-class-methods)Returns a new string with $suffix appended.

EXAMPLE: ``

**Parameters:**

- `CollectionStringy|static ...$suffix The Stringy objects to append.`

**Return:**

- `static Object with appended $suffix.`

---

appendUniqueIdentifier(int|string $entropyExtra, bool $md5): static
-------------------------------------------------------------------

[](#appenduniqueidentifierintstring-entropyextra-bool-md5-static)

[↑](#voku-php-readme-class-methods)Append an unique identifier.

EXAMPLE: `s('')->appendUniqueIdentifier(); // e.g.: '1f3870be274f6c49b3e31a0c6728957f'`

**Parameters:**

- `int|string $entropyExtra [optional] Extra entropy via a string or int value.`
- `bool $md5 [optional] Return the unique identifier as md5-hash? Default: true`

**Return:**

- `static Object with appended unique identifier as md5-hash.`

---

at(int $index): static
----------------------

[](#atint-index-static)

[↑](#voku-php-readme-class-methods)Returns the character at $index, with indexes starting at 0.

EXAMPLE: `s('fòôbàř')->at(3); // 'b'`

**Parameters:**

- `int $index Position of the character.`

**Return:**

- `static The character at $index.`

---

base64Decode(): self
--------------------

[](#base64decode-self)

[↑](#voku-php-readme-class-methods)Decode the base64 encoded string.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `self`

---

base64Encode(): self
--------------------

[](#base64encode-self)

[↑](#voku-php-readme-class-methods)Encode the string to base64.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `self`

---

bcrypt(int\[\]|string\[\] $options): static
-------------------------------------------

[](#bcryptintstring-options-static)

[↑](#voku-php-readme-class-methods)Creates a hash from the string using the CRYPT\_BLOWFISH algorithm.

WARNING: Using this algorithm, will result in the `$this->str`being truncated to a maximum length of 72 characters.

EXAMPLE: ``

**Parameters:**

- `array $options [optional] An array of bcrypt hashing options.`

**Return:**

- `static`

---

before(string $string): static
------------------------------

[](#beforestring-string-static)

[↑](#voku-php-readme-class-methods)Return part of the string occurring before a specific string.

EXAMPLE: ``

**Parameters:**

- `string $string The delimiting string.`

**Return:**

- `static`

---

beforeFirst(string $separator): static
--------------------------------------

[](#beforefirststring-separator-static)

[↑](#voku-php-readme-class-methods)Gets the substring before the first occurrence of a separator.

If no match is found returns new empty Stringy object.

EXAMPLE: `s('')->beforeFirst('b'); // 'capitalizePersonName(); // 'Jaap de Hoop Scheffer'`

**Parameters:****nothing**

**Return:**

- `static Object with $str capitalized.`

---

chars(): string\[\]
-------------------

[](#chars-string)

[↑](#voku-php-readme-class-methods)Returns an array consisting of the characters in the string.

EXAMPLE: `s('fòôbàř')->chars(); // ['f', 'ò', 'ô', 'b', 'à', 'ř']`

**Parameters:****nothing**

**Return:**

- `string[] An array of string chars.`

---

chunk(int $length): static\[\]
------------------------------

[](#chunkint-length-static)

[↑](#voku-php-readme-class-methods)Splits the string into chunks of Stringy objects.

EXAMPLE: `s('foobar')->chunk(3); // ['foo', 'bar']`

**Parameters:**

- `int $length [optional] Max character length of each array element.`

**Return:**

- `static[] An array of Stringy objects.`

---

chunkCollection(int $length): CollectionStringy|static\[\]
----------------------------------------------------------

[](#chunkcollectionint-length-collectionstringystatic)

[↑](#voku-php-readme-class-methods)Splits the string into chunks of Stringy objects collection.

EXAMPLE: ``

**Parameters:**

- `int $length [optional] Max character length of each array element.`

**Return:**

- `\CollectionStringy|static[] An collection of Stringy objects.`

---

collapseWhitespace(): static
----------------------------

[](#collapsewhitespace-static)

[↑](#voku-php-readme-class-methods)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.

EXAMPLE: `s('   Ο     συγγραφέας  ')->collapseWhitespace(); // 'Ο συγγραφέας'`

**Parameters:****nothing**

**Return:**

- `static Object with a trimmed $str and condensed whitespace.`

---

contains(string $needle, bool $caseSensitive): bool
---------------------------------------------------

[](#containsstring-needle-bool-casesensitive-bool)

[↑](#voku-php-readme-class-methods)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.

EXAMPLE: `s('Ο συγγραφέας είπε')->contains('συγγραφέας'); // true`

**Parameters:**

- `string $needle Substring to look for.`
- `bool $caseSensitive [optional] Whether or not to enforce case-sensitivity. Default: true`

**Return:**

- `bool Whether or not $str contains $needle.`

---

containsAll(string\[\] $needles, bool $caseSensitive): bool
-----------------------------------------------------------

[](#containsallstring-needles-bool-casesensitive-bool)

[↑](#voku-php-readme-class-methods)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.

EXAMPLE: `s('foo & bar')->containsAll(['foo', 'bar']); // true`

**Parameters:**

- `string[] $needles SubStrings to look for.`
- `bool $caseSensitive [optional] Whether or not to enforce case-sensitivity. Default: true`

**Return:**

- `bool Whether or not $str contains $needle.`

---

containsAny(string\[\] $needles, bool $caseSensitive): bool
-----------------------------------------------------------

[](#containsanystring-needles-bool-casesensitive-bool)

[↑](#voku-php-readme-class-methods)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.

EXAMPLE: `s('str contains foo')->containsAny(['foo', 'bar']); // true`

**Parameters:**

- `string[] $needles SubStrings to look for.`
- `bool $caseSensitive [optional] Whether or not to enforce case-sensitivity. Default: true`

**Return:**

- `bool Whether or not $str contains $needle.`

---

containsBom(): bool
-------------------

[](#containsbom-bool)

[↑](#voku-php-readme-class-methods)Checks if string starts with "BOM" (Byte Order Mark Character) character.

EXAMPLE: `s("\xef\xbb\xbf foobar")->containsBom(); // true`

**Parameters:****nothing**

**Return:**

- `bool true if the string has BOM at the start, false otherwise`

---

count(): int
------------

[](#count-int)

[↑](#voku-php-readme-class-methods)Returns the length of the string, implementing the countable interface.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `int The number of characters in the string, given the encoding.`

---

countSubstr(string $substring, bool $caseSensitive): int
--------------------------------------------------------

[](#countsubstrstring-substring-bool-casesensitive-int)

[↑](#voku-php-readme-class-methods)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.

EXAMPLE: `s('Ο συγγραφέας είπε')->countSubstr('α'); // 2`

**Parameters:**

- `string $substring The substring to search for.`
- `bool $caseSensitive [optional] Whether or not to enforce case-sensitivity. Default: true`

**Return:**

- `int`

---

crc32(): int
------------

[](#crc32-int)

[↑](#voku-php-readme-class-methods)Calculates the crc32 polynomial of a string.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `int`

---

create(mixed $str, string $encoding): static
--------------------------------------------

[](#createmixed-str-string-encoding-static)

[↑](#voku-php-readme-class-methods)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.

**Parameters:**

- `mixed $str [optional] Value to modify, after being cast to string. Default: ''`
- `string $encoding [optional] The character encoding. Fallback: 'UTF-8'`

**Return:**

- `static A Stringy object.`

---

crypt(string $salt): static
---------------------------

[](#cryptstring-salt-static)

[↑](#voku-php-readme-class-methods)One-way string encryption (hashing).

Hash the string using the standard Unix DES-based algorithm or an alternative algorithm that may be available on the system.

PS: if you need encrypt / decrypt, please use `static::encrypt($password)`and `static::decrypt($password)`

EXAMPLE: ``

**Parameters:**

- `string $salt A salt string to base the hashing on.`

**Return:**

- `static`

---

dasherize(): static
-------------------

[](#dasherize-static)

[↑](#voku-php-readme-class-methods)Returns a lowercase and trimmed string separated by dashes. Dashes are inserted before uppercase characters (with the exception of the first character of the string), and in place of spaces as well as underscores.

EXAMPLE: `s('fooBar')->dasherize(); // 'foo-bar'`

**Parameters:****nothing**

**Return:**

- `static Object with a dasherized $str`

---

decrypt(string $password): static
---------------------------------

[](#decryptstring-password-static)

[↑](#voku-php-readme-class-methods)Decrypt the string.

EXAMPLE: ``

**Parameters:**

- `string $password The key for decrypting`

**Return:**

- `static`

---

delimit(string $delimiter): static
----------------------------------

[](#delimitstring-delimiter-static)

[↑](#voku-php-readme-class-methods)Returns a lowercase and trimmed string separated by the given delimiter.

Delimiters are inserted before uppercase characters (with the exception of the first character of the string), and in place of spaces, dashes, and underscores. Alpha delimiters are not converted to lowercase.

EXAMPLE: `s('fooBar')->delimit('::'); // 'foo::bar'`

**Parameters:**

- `string $delimiter Sequence used to separate parts of the string.`

**Return:**

- `static Object with a delimited $str.`

---

encode(string $new\_encoding, bool $auto\_detect\_encoding): static
-------------------------------------------------------------------

[](#encodestring-new_encoding-bool-auto_detect_encoding-static)

[↑](#voku-php-readme-class-methods)Encode the given string into the given $encoding + set the internal character encoding.

EXAMPLE: ``

**Parameters:**

- `string $new_encoding The desired character encoding.`
- `bool $auto_detect_encoding [optional] Auto-detect the current string-encoding`

**Return:**

- `static`

---

encrypt(string $password): static
---------------------------------

[](#encryptstring-password-static)

[↑](#voku-php-readme-class-methods)Encrypt the string.

EXAMPLE: ``

**Parameters:**

- `string $password The key for encrypting`

**Return:**

- `static`

---

endsWith(string $substring, bool $caseSensitive): bool
------------------------------------------------------

[](#endswithstring-substring-bool-casesensitive-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string ends with $substring, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.

EXAMPLE: `s('fòôbàř')->endsWith('bàř', true); // true`

**Parameters:**

- `string $substring The substring to look for.`
- `bool $caseSensitive [optional] Whether or not to enforce case-sensitivity. Default: true`

**Return:**

- `bool Whether or not $str ends with $substring.`

---

endsWithAny(string\[\] $substrings, bool $caseSensitive): bool
--------------------------------------------------------------

[](#endswithanystring-substrings-bool-casesensitive-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string ends with any of $substrings, false otherwise.

By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.

EXAMPLE: `s('fòôbàř')->endsWithAny(['bàř', 'baz'], true); // true`

**Parameters:**

- `string[] $substrings Substrings to look for.`
- `bool $caseSensitive [optional] Whether or not to enforce case-sensitivity. Default: true`

**Return:**

- `bool Whether or not $str ends with $substring.`

---

ensureLeft(string $substring): static
-------------------------------------

[](#ensureleftstring-substring-static)

[↑](#voku-php-readme-class-methods)Ensures that the string begins with $substring. If it doesn't, it's prepended.

EXAMPLE: `s('foobar')->ensureLeft('http://'); // 'http://foobar'`

**Parameters:**

- `string $substring The substring to add if not present.`

**Return:**

- `static Object with its $str prefixed by the $substring.`

---

ensureRight(string $substring): static
--------------------------------------

[](#ensurerightstring-substring-static)

[↑](#voku-php-readme-class-methods)Ensures that the string ends with $substring. If it doesn't, it's appended.

EXAMPLE: `s('foobar')->ensureRight('.com'); // 'foobar.com'`

**Parameters:**

- `string $substring The substring to add if not present.`

**Return:**

- `static Object with its $str suffixed by the $substring.`

---

escape(): static
----------------

[](#escape-static)

[↑](#voku-php-readme-class-methods)Create a escape html version of the string via "htmlspecialchars()".

EXAMPLE: `s('')->escape(); // ''`

**Parameters:****nothing**

**Return:**

- `static`

---

explode(string $delimiter, int $limit): array&lt;int,static&gt;
---------------------------------------------------------------

[](#explodestring-delimiter-int-limit-arrayintstatic)

[↑](#voku-php-readme-class-methods)Split a string by a string.

EXAMPLE: ``

**Parameters:**

- `string $delimiter The boundary string`
- `int $limit \[optional\]

    The maximum number of elements in the exploded collection.
- If limit is set and positive, the returned collection will contain a maximum of limit elements with the last element containing the rest of string.
- If the limit parameter is negative, all components except the last -limit are returned.
- If the limit parameter is zero, then this is treated as 1`

**Return:**

- `array`

---

explodeCollection(string $delimiter, int $limit): CollectionStringy|static\[\]
------------------------------------------------------------------------------

[](#explodecollectionstring-delimiter-int-limit-collectionstringystatic)

[↑](#voku-php-readme-class-methods)Split a string by a string.

EXAMPLE: ``

**Parameters:**

- `string $delimiter The boundary string`
- `int $limit \[optional\]

    The maximum number of elements in the exploded collection.
- If limit is set and positive, the returned collection will contain a maximum of limit elements with the last element containing the rest of string.
- If the limit parameter is negative, all components except the last -limit are returned.
- If the limit parameter is zero, then this is treated as 1`

**Return:**

- `\CollectionStringy|static[] An collection of Stringy objects.`

---

extractIntegers(): static
-------------------------

[](#extractintegers-static)

[↑](#voku-php-readme-class-methods)Returns the integer value of the current string.

EXAMPLE: `s('foo1 ba2r')->extractIntegers(); // '12'`

**Parameters:****nothing**

**Return:**

- `static`

---

extractSpecialCharacters(): static
----------------------------------

[](#extractspecialcharacters-static)

[↑](#voku-php-readme-class-methods)Returns the special chars of the current string.

EXAMPLE: `s('foo1 ba2!r')->extractSpecialCharacters(); // '!'`

**Parameters:****nothing**

**Return:**

- `static`

---

extractText(string $search, int|null $length, string $replacerForSkippedText): static
-------------------------------------------------------------------------------------

[](#extracttextstring-search-intnull-length-string-replacerforskippedtext-static)

[↑](#voku-php-readme-class-methods)Create an extract from a sentence, so if the search-string was found, it try to centered in the output.

EXAMPLE: `$sentence = 'This is only a Fork of Stringy, take a look at the new features.';s($sentence)->extractText('Stringy'); // '...Fork of Stringy...'`

**Parameters:**

- `string $search`
- `int|null $length [optional] Default: null === text->length / 2`
- `string $replacerForSkippedText [optional] Default: …`

**Return:**

- `static`

---

first(int $n): static
---------------------

[](#firstint-n-static)

[↑](#voku-php-readme-class-methods)Returns the first $n characters of the string.

EXAMPLE: `s('fòôbàř')->first(3); // 'fòô'`

**Parameters:**

- `int $n Number of characters to retrieve from the start.`

**Return:**

- `static Object with its $str being the first $n chars.`

---

format(mixed $args): static
---------------------------

[](#formatmixed-args-static)

[↑](#voku-php-readme-class-methods)Return a formatted string via sprintf + named parameters via array syntax.

It will use "sprintf()" so you can use e.g.:

```
s('There are %d monkeys in the %s')->format(5, 'tree');
```

```
s('There are %2$d monkeys in the %1$s')->format('tree', 5);
```

But you can also use named parameter via array syntax e.g.:

```
s('There are %:count monkeys in the %:location')->format(['count' => 5, 'location' => 'tree');
```

EXAMPLE: `$input = 'one: %2$d, %1$s: 2, %:text_three: %3$d';s($input)->format(['text_three' => '%4$s'], 'two', 1, 3, 'three'); // 'One: 1, two: 2, three: 3'`

**Parameters:**

- `mixed ...$args [optional]`

**Return:**

- `static A Stringy object produced according to the formatting string format.`

---

getEncoding(): string
---------------------

[](#getencoding-string)

[↑](#voku-php-readme-class-methods)Returns the encoding used by the Stringy object.

EXAMPLE: `s('fòôbàř', 'UTF-8')->getEncoding(); // 'UTF-8'`

**Parameters:****nothing**

**Return:**

- `string The current value of the $encoding property.`

---

getIterator(): ArrayIterator
----------------------------

[](#getiterator-arrayiterator)

[↑](#voku-php-readme-class-methods)Returns a new ArrayIterator, thus implementing the IteratorAggregate interface. The ArrayIterator's constructor is passed an array of chars in the multibyte string. This enables the use of foreach with instances of Stringy\\Stringy.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `\ArrayIterator An iterator for the characters in the string.`

---

hardWrap(int $width, string $break): static
-------------------------------------------

[](#hardwrapint-width-string-break-static)

[↑](#voku-php-readme-class-methods)Wrap the string after an exact number of characters.

EXAMPLE: ``

**Parameters:**

- `int $width Number of characters at which to wrap.`
- `string $break [optional] Character used to break the string. | Default: "\n"`

**Return:**

- `static`

---

hasLowerCase(): bool
--------------------

[](#haslowercase-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string contains a lower case char, false otherwise

EXAMPLE: `s('fòôbàř')->hasLowerCase(); // true`

**Parameters:****nothing**

**Return:**

- `bool Whether or not the string contains a lower case character.`

---

hasUpperCase(): bool
--------------------

[](#hasuppercase-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string contains an upper case char, false otherwise.

EXAMPLE: `s('fòôbàř')->hasUpperCase(); // false`

**Parameters:****nothing**

**Return:**

- `bool Whether or not the string contains an upper case character.`

---

hash(string $algorithm): static
-------------------------------

[](#hashstring-algorithm-static)

[↑](#voku-php-readme-class-methods)Generate a hash value (message digest).

EXAMPLE: ``

**Parameters:**

- `string $algorithm Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)`

**Return:**

- `static`

---

hexDecode(): static
-------------------

[](#hexdecode-static)

[↑](#voku-php-readme-class-methods)Decode the string from hex.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

hexEncode(): static
-------------------

[](#hexencode-static)

[↑](#voku-php-readme-class-methods)Encode string to hex.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

htmlDecode(int $flags): static
------------------------------

[](#htmldecodeint-flags-static)

[↑](#voku-php-readme-class-methods)Convert all HTML entities to their applicable characters.

EXAMPLE: `s('&')->htmlDecode(); // '&'`

**Parameters:**

- `int $flags \[optional\] A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. The default is ENT\_COMPAT.

Available *flags* constants Constant NameDescription**ENT\_COMPAT**Will convert double-quotes and leave single-quotes alone.**ENT\_QUOTES**Will convert both double and single quotes.**ENT\_NOQUOTES**Will leave both double and single quotes unconverted.**ENT\_HTML401**Handle code as HTML 4.01. **ENT\_XML1**Handle code as XML 1. **ENT\_XHTML**Handle code as XHTML. **ENT\_HTML5**Handle code as HTML 5. ` **Return:**

- `static Object with the resulting $str after being html decoded.`

---

htmlEncode(int $flags): static
------------------------------

[](#htmlencodeint-flags-static)

[↑](#voku-php-readme-class-methods)Convert all applicable characters to HTML entities.

EXAMPLE: `s('&')->htmlEncode(); // '&'`

**Parameters:**

- `int $flags \[optional\] A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. The default is ENT\_COMPAT.

Available *flags* constants Constant NameDescription**ENT\_COMPAT**Will convert double-quotes and leave single-quotes alone.**ENT\_QUOTES**Will convert both double and single quotes.**ENT\_NOQUOTES**Will leave both double and single quotes unconverted.**ENT\_HTML401**Handle code as HTML 4.01. **ENT\_XML1**Handle code as XML 1. **ENT\_XHTML**Handle code as XHTML. **ENT\_HTML5**Handle code as HTML 5. ` **Return:**

- `static Object with the resulting $str after being html encoded.`

---

humanize(): static
------------------

[](#humanize-static)

[↑](#voku-php-readme-class-methods)Capitalizes the first word of the string, replaces underscores with spaces, and strips '\_id'.

EXAMPLE: `s('author_id')->humanize(); // 'Author'`

**Parameters:****nothing**

**Return:**

- `static Object with a humanized $str.`

---

in(string $str, bool $caseSensitive): bool
------------------------------------------

[](#instring-str-bool-casesensitive-bool)

[↑](#voku-php-readme-class-methods)Determine if the current string exists in another string. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.

EXAMPLE: ``

**Parameters:**

- `string $str The string to compare against.`
- `bool $caseSensitive [optional] Whether or not to enforce case-sensitivity. Default: true`

**Return:**

- `bool`

---

indexOf(string $needle, int $offset): false|int
-----------------------------------------------

[](#indexofstring-needle-int-offset-falseint)

[↑](#voku-php-readme-class-methods)Returns the index of the first occurrence of $needle in the string, and false if not found. Accepts an optional offset from which to begin the search.

EXAMPLE: `s('string')->indexOf('ing'); // 3`

**Parameters:**

- `string $needle Substring to look for.`
- `int $offset [optional] Offset from which to search. Default: 0`

**Return:**

- `false|int The occurrence's index if found, otherwise false.`

---

indexOfIgnoreCase(string $needle, int $offset): false|int
---------------------------------------------------------

[](#indexofignorecasestring-needle-int-offset-falseint)

[↑](#voku-php-readme-class-methods)Returns the index of the first occurrence of $needle in the string, and false if not found. Accepts an optional offset from which to begin the search.

EXAMPLE: `s('string')->indexOfIgnoreCase('ING'); // 3`

**Parameters:**

- `string $needle Substring to look for.`
- `int $offset [optional] Offset from which to search. Default: 0`

**Return:**

- `false|int The occurrence's index if found, otherwise false.`

---

indexOfLast(string $needle, int $offset): false|int
---------------------------------------------------

[](#indexoflaststring-needle-int-offset-falseint)

[↑](#voku-php-readme-class-methods)Returns the index of the last occurrence of $needle in the string, and false if not found. Accepts an optional offset from which to begin the search. Offsets may be negative to count from the last character in the string.

EXAMPLE: `s('foobarfoo')->indexOfLast('foo'); // 10`

**Parameters:**

- `string $needle Substring to look for.`
- `int $offset [optional] Offset from which to search. Default: 0`

**Return:**

- `false|int The last occurrence's index if found, otherwise false.`

---

indexOfLastIgnoreCase(string $needle, int $offset): false|int
-------------------------------------------------------------

[](#indexoflastignorecasestring-needle-int-offset-falseint)

[↑](#voku-php-readme-class-methods)Returns the index of the last occurrence of $needle in the string, and false if not found. Accepts an optional offset from which to begin the search. Offsets may be negative to count from the last character in the string.

EXAMPLE: `s('fooBarFoo')->indexOfLastIgnoreCase('foo'); // 10`

**Parameters:**

- `string $needle Substring to look for.`
- `int $offset [optional] Offset from which to search. Default: 0`

**Return:**

- `false|int The last occurrence's index if found, otherwise false.`

---

insert(string $substring, int $index): static
---------------------------------------------

[](#insertstring-substring-int-index-static)

[↑](#voku-php-readme-class-methods)Inserts $substring into the string at the $index provided.

EXAMPLE: `s('fòôbř')->insert('à', 4); // 'fòôbàř'`

**Parameters:**

- `string $substring String to be inserted.`
- `int $index The index at which to insert the substring.`

**Return:**

- `static Object with the resulting $str after the insertion.`

---

is(string $pattern): bool
-------------------------

[](#isstring-pattern-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string contains the $pattern, otherwise false.

WARNING: Asterisks ("*") are translated into (".*") zero-or-more regular expression wildcards.

EXAMPLE: `s('Foo\Bar\Lall')->is('\Bar\'); // true`

**Parameters:**

- `string $pattern The string or pattern to match against.`

**Return:**

- `bool Whether or not we match the provided pattern.`

---

isAlpha(): bool
---------------

[](#isalpha-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string contains only alphabetic chars, false otherwise.

EXAMPLE: `s('丹尼爾')->isAlpha(); // true`

**Parameters:****nothing**

**Return:**

- `bool Whether or not $str contains only alphabetic chars.`

---

isAlphanumeric(): bool
----------------------

[](#isalphanumeric-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string contains only alphabetic and numeric chars, false otherwise.

EXAMPLE: `s('دانيال1')->isAlphanumeric(); // true`

**Parameters:****nothing**

**Return:**

- `bool Whether or not $str contains only alphanumeric chars.`

---

isAscii(): bool
---------------

[](#isascii-bool)

[↑](#voku-php-readme-class-methods)Checks if a string is 7 bit ASCII.

EXAMPLE: `s('白')->isAscii; // false`

**Parameters:****nothing**

**Return:**

- `bool **true** if it is ASCII
    **false** otherwise

` ---

isBase64(bool $emptyStringIsValid): bool
----------------------------------------

[](#isbase64bool-emptystringisvalid-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string is base64 encoded, false otherwise.

EXAMPLE: `s('Zm9vYmFy')->isBase64(); // true`

**Parameters:**

- `bool $emptyStringIsValid`

**Return:**

- `bool Whether or not $str is base64 encoded.`

---

isBinary(): bool
----------------

[](#isbinary-bool)

[↑](#voku-php-readme-class-methods)Check if the input is binary... (is look like a hack).

EXAMPLE: `s(01)->isBinary(); // true`

**Parameters:****nothing**

**Return:**

- `bool`

---

isBlank(): bool
---------------

[](#isblank-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string contains only whitespace chars, false otherwise.

EXAMPLE: `s("\n\t  \v\f")->isBlank(); // true`

**Parameters:****nothing**

**Return:**

- `bool Whether or not $str contains only whitespace characters.`

---

isBom(): bool
-------------

[](#isbom-bool)

[↑](#voku-php-readme-class-methods)Checks if the given string is equal to any "Byte Order Mark".

WARNING: Use "s::string\_has\_bom()" if you will check BOM in a string.

EXAMPLE: `s->("\xef\xbb\xbf")->isBom(); // true`

**Parameters:****nothing**

**Return:**

- `bool true if the $utf8_chr is Byte Order Mark, false otherwise.`

---

isEmail(bool $useExampleDomainCheck, bool $useTypoInDomainCheck, bool $useTemporaryDomainCheck, bool $useDnsCheck): bool
------------------------------------------------------------------------------------------------------------------------

[](#isemailbool-useexampledomaincheck-bool-usetypoindomaincheck-bool-usetemporarydomaincheck-bool-usednscheck-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string contains a valid E-Mail address, false otherwise.

EXAMPLE: `s('lars@moelleken.org')->isEmail(); // true`

**Parameters:**

- `bool $useExampleDomainCheck [optional] Default: false`
- `bool $useTypoInDomainCheck [optional] Default: false`
- `bool $useTemporaryDomainCheck [optional] Default: false`
- `bool $useDnsCheck [optional] Default: false`

**Return:**

- `bool Whether or not $str contains a valid E-Mail address.`

---

isEmpty(): bool
---------------

[](#isempty-bool)

[↑](#voku-php-readme-class-methods)Determine whether the string is considered to be empty.

A variable is considered empty if it does not exist or if its value equals FALSE.

EXAMPLE: `s('')->isEmpty(); // true`

**Parameters:****nothing**

**Return:**

- `bool Whether or not $str is empty().`

---

isEquals(string|\\Stringy $str): bool
-------------------------------------

[](#isequalsstringstringy-str-bool)

[↑](#voku-php-readme-class-methods)Determine whether the string is equals to $str.

Alias for isEqualsCaseSensitive()

EXAMPLE: `s('foo')->isEquals('foo'); // true`

**Parameters:**

- `string|\Stringy ...$str`

**Return:**

- `bool`

---

isEqualsCaseInsensitive(float|int|string|\\Stringy $str): bool
--------------------------------------------------------------

[](#isequalscaseinsensitivefloatintstringstringy-str-bool)

[↑](#voku-php-readme-class-methods)Determine whether the string is equals to $str.

EXAMPLE: ``

**Parameters:**

- `float|int|string|\Stringy ...$str The string to compare.`

**Return:**

- `bool Whether or not $str is equals.`

---

isEqualsCaseSensitive(float|int|string|\\Stringy $str): bool
------------------------------------------------------------

[](#isequalscasesensitivefloatintstringstringy-str-bool)

[↑](#voku-php-readme-class-methods)Determine whether the string is equals to $str.

EXAMPLE: ``

**Parameters:**

- `float|int|string|\Stringy ...$str The string to compare.`

**Return:**

- `bool Whether or not $str is equals.`

---

isHexadecimal(): bool
---------------------

[](#ishexadecimal-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string contains only hexadecimal chars, false otherwise.

EXAMPLE: `s('A102F')->isHexadecimal(); // true`

**Parameters:****nothing**

**Return:**

- `bool Whether or not $str contains only hexadecimal chars.`

---

isHtml(): bool
--------------

[](#ishtml-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string contains HTML-Tags, false otherwise.

EXAMPLE: `s('`

`foo`
=====

[](#foo)

`')->isHtml(); // true`**Parameters:****nothing**

**Return:**

- `bool Whether or not $str contains HTML-Tags.`

---

isJson(bool $onlyArrayOrObjectResultsAreValid): bool
----------------------------------------------------

[](#isjsonbool-onlyarrayorobjectresultsarevalid-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string is JSON, false otherwise. Unlike json\_decode in PHP 5.x, this method is consistent with PHP 7 and other JSON parsers, in that an empty string is not considered valid JSON.

EXAMPLE: `s('{"foo":"bar"}')->isJson(); // true`

**Parameters:**

- `bool $onlyArrayOrObjectResultsAreValid`

**Return:**

- `bool Whether or not $str is JSON.`

---

isLowerCase(): bool
-------------------

[](#islowercase-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string contains only lower case chars, false otherwise.

EXAMPLE: `s('fòôbàř')->isLowerCase(); // true`

**Parameters:****nothing**

**Return:**

- `bool Whether or not $str contains only lower case characters.`

---

isNotEmpty(): bool
------------------

[](#isnotempty-bool)

[↑](#voku-php-readme-class-methods)Determine whether the string is considered to be NOT empty.

A variable is considered NOT empty if it does exist or if its value equals TRUE.

EXAMPLE: `s('')->isNotEmpty(); // false`

**Parameters:****nothing**

**Return:**

- `bool Whether or not $str is empty().`

---

isNumeric(): bool
-----------------

[](#isnumeric-bool)

[↑](#voku-php-readme-class-methods)Determine if the string is composed of numeric characters.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `bool`

---

isPrintable(): bool
-------------------

[](#isprintable-bool)

[↑](#voku-php-readme-class-methods)Determine if the string is composed of printable (non-invisible) characters.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `bool`

---

isPunctuation(): bool
---------------------

[](#ispunctuation-bool)

[↑](#voku-php-readme-class-methods)Determine if the string is composed of punctuation characters.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `bool`

---

isSerialized(): bool
--------------------

[](#isserialized-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string is serialized, false otherwise.

EXAMPLE: `s('a:1:{s:3:"foo";s:3:"bar";}')->isSerialized(); // true`

**Parameters:****nothing**

**Return:**

- `bool Whether or not $str is serialized.`

---

isSimilar(string $str, float $minPercentForSimilarity): bool
------------------------------------------------------------

[](#issimilarstring-str-float-minpercentforsimilarity-bool)

[↑](#voku-php-readme-class-methods)Check if two strings are similar.

EXAMPLE: ``

**Parameters:**

- `string $str The string to compare against.`
- `float $minPercentForSimilarity [optional] The percentage of needed similarity. | Default: 80%`

**Return:**

- `bool`

---

isUpperCase(): bool
-------------------

[](#isuppercase-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string contains only lower case chars, false otherwise.

EXAMPLE: `s('FÒÔBÀŘ')->isUpperCase(); // true`

**Parameters:****nothing**

**Return:**

- `bool Whether or not $str contains only lower case characters.`

---

isUrl(bool $disallow\_localhost): bool
--------------------------------------

[](#isurlbool-disallow_localhost-bool)

[↑](#voku-php-readme-class-methods)/\*\* Check if $url is an correct url.

**Parameters:**

- `bool $disallow_localhost`

**Return:**

- `bool`

---

isUtf8(bool $strict): bool
--------------------------

[](#isutf8bool-strict-bool)

[↑](#voku-php-readme-class-methods)Checks whether the passed input contains only byte sequences that appear valid UTF-8.

EXAMPLE: `s('Iñtërnâtiônàlizætiøn')->isUtf8(); // true//s("Iñtërnâtiônàlizætiøn\xA0\xA1")->isUtf8(); // false`

**Parameters:**

- `bool $strict Check also if the string is not UTF-16 or UTF-32.`

**Return:**

- `bool`

---

isUtf16(): false|int
--------------------

[](#isutf16-falseint)

[↑](#voku-php-readme-class-methods)Check if the string is UTF-16.

**Parameters:****nothing**

**Return:**

- `false|int false if is't not UTF-16, 1 for UTF-16LE, 2 for UTF-16BE`

---

isUtf32(): false|int
--------------------

[](#isutf32-falseint)

[↑](#voku-php-readme-class-methods)Check if the string is UTF-32.

**Parameters:****nothing**

**Return:**

- `false|int false if is't not UTF-32, 1 for UTF-32LE, 2 for UTF-32BE`

---

isWhitespace(): bool
--------------------

[](#iswhitespace-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string contains only whitespace chars, false otherwise.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `bool Whether or not $str contains only whitespace characters.`

---

jsonSerialize(): string
-----------------------

[](#jsonserialize-string)

[↑](#voku-php-readme-class-methods)Returns value which can be serialized by json\_encode().

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `string The current value of the $str property`

---

kebabCase(): static
-------------------

[](#kebabcase-static)

[↑](#voku-php-readme-class-methods)Convert the string to kebab-case.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

last(int $n): static
--------------------

[](#lastint-n-static)

[↑](#voku-php-readme-class-methods)Returns the last $n characters of the string.

EXAMPLE: `s('fòôbàř')->last(3); // 'bàř'`

**Parameters:**

- `int $n Number of characters to retrieve from the end.`

**Return:**

- `static Object with its $str being the last $n chars.`

---

lastSubstringOf(string $needle, bool $beforeNeedle): static
-----------------------------------------------------------

[](#lastsubstringofstring-needle-bool-beforeneedle-static)

[↑](#voku-php-readme-class-methods)Gets the substring after (or before via "$beforeNeedle") the last occurrence of the "$needle".

If no match is found returns new empty Stringy object.

EXAMPLE: ``

**Parameters:**

- `string $needle The string to look for.`
- `bool $beforeNeedle [optional] Default: false`

**Return:**

- `static`

---

lastSubstringOfIgnoreCase(string $needle, bool $beforeNeedle): static
---------------------------------------------------------------------

[](#lastsubstringofignorecasestring-needle-bool-beforeneedle-static)

[↑](#voku-php-readme-class-methods)Gets the substring after (or before via "$beforeNeedle") the last occurrence of the "$needle".

If no match is found returns new empty Stringy object.

EXAMPLE: ``

**Parameters:**

- `string $needle The string to look for.`
- `bool $beforeNeedle [optional] Default: false`

**Return:**

- `static`

---

length(): int
-------------

[](#length-int)

[↑](#voku-php-readme-class-methods)Returns the length of the string.

EXAMPLE: `s('fòôbàř')->length(); // 6`

**Parameters:****nothing**

**Return:**

- `int The number of characters in $str given the encoding.`

---

lineWrap(int $limit, string $break, bool $add\_final\_break, string|null $delimiter): static
--------------------------------------------------------------------------------------------

[](#linewrapint-limit-string-break-bool-add_final_break-stringnull-delimiter-static)

[↑](#voku-php-readme-class-methods)Line-Wrap the string after $limit, but also after the next word.

EXAMPLE: ``

**Parameters:**

- `int $limit [optional] The column width.`
- `string $break [optional] The line is broken using the optional break parameter.`
- `bool $add\_final\_break \[optional\] If this flag is true, then the method will add a $break at the end of the result string.

` - `string|null $delimiter \[optional\] You can change the default behavior, where we split the string by newline.

` **Return:**

- `static`

---

lineWrapAfterWord(int $limit, string $break, bool $add\_final\_break, string|null $delimiter): static
-----------------------------------------------------------------------------------------------------

[](#linewrapafterwordint-limit-string-break-bool-add_final_break-stringnull-delimiter-static)

[↑](#voku-php-readme-class-methods)Line-Wrap the string after $limit, but also after the next word.

EXAMPLE: ``

**Parameters:**

- `int $limit [optional] The column width.`
- `string $break [optional] The line is broken using the optional break parameter.`
- `bool $add\_final\_break \[optional\] If this flag is true, then the method will add a $break at the end of the result string.

` - `string|null $delimiter \[optional\] You can change the default behavior, where we split the string by newline.

` **Return:**

- `static`

---

lines(): static\[\]
-------------------

[](#lines-static)

[↑](#voku-php-readme-class-methods)Splits on newlines and carriage returns, returning an array of Stringy objects corresponding to the lines in the string.

EXAMPLE: `s("fòô\r\nbàř\n")->lines(); // ['fòô', 'bàř', '']`

**Parameters:****nothing**

**Return:**

- `static[] An array of Stringy objects.`

---

linesCollection(): CollectionStringy|static\[\]
-----------------------------------------------

[](#linescollection-collectionstringystatic)

[↑](#voku-php-readme-class-methods)Splits on newlines and carriage returns, returning an array of Stringy objects corresponding to the lines in the string.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `\CollectionStringy|static[] An collection of Stringy objects.`

---

longestCommonPrefix(string $otherStr): static
---------------------------------------------

[](#longestcommonprefixstring-otherstr-static)

[↑](#voku-php-readme-class-methods)Returns the longest common prefix between the string and $otherStr.

EXAMPLE: `s('foobar')->longestCommonPrefix('foobaz'); // 'fooba'`

**Parameters:**

- `string $otherStr Second string for comparison.`

**Return:**

- `static Object with its $str being the longest common prefix.`

---

longestCommonSubstring(string $otherStr): static
------------------------------------------------

[](#longestcommonsubstringstring-otherstr-static)

[↑](#voku-php-readme-class-methods)Returns the longest common substring between the string and $otherStr.

In the case of ties, it returns that which occurs first.

EXAMPLE: `s('foobar')->longestCommonSubstring('boofar'); // 'oo'`

**Parameters:**

- `string $otherStr Second string for comparison.`

**Return:**

- `static Object with its $str being the longest common substring.`

---

longestCommonSuffix(string $otherStr): static
---------------------------------------------

[](#longestcommonsuffixstring-otherstr-static)

[↑](#voku-php-readme-class-methods)Returns the longest common suffix between the string and $otherStr.

EXAMPLE: `s('fòôbàř')->longestCommonSuffix('fòrbàř'); // 'bàř'`

**Parameters:**

- `string $otherStr Second string for comparison.`

**Return:**

- `static Object with its $str being the longest common suffix.`

---

lowerCaseFirst(): static
------------------------

[](#lowercasefirst-static)

[↑](#voku-php-readme-class-methods)Converts the first character of the string to lower case.

EXAMPLE: `s('Σ Foo')->lowerCaseFirst(); // 'σ Foo'`

**Parameters:****nothing**

**Return:**

- `static Object with the first character of $str being lower case.`

---

matchCaseInsensitive(string|\\Stringy $str): bool
-------------------------------------------------

[](#matchcaseinsensitivestringstringy-str-bool)

[↑](#voku-php-readme-class-methods)Determine if the string matches another string regardless of case.

Alias for isEqualsCaseInsensitive()

EXAMPLE: ``

**Parameters:**

- `string|\Stringy ...$str The string to compare against.`

**Return:**

- `bool`

---

matchCaseSensitive(string|\\Stringy $str): bool
-----------------------------------------------

[](#matchcasesensitivestringstringy-str-bool)

[↑](#voku-php-readme-class-methods)Determine if the string matches another string.

Alias for isEqualsCaseSensitive()

EXAMPLE: ``

**Parameters:**

- `string|\Stringy ...$str The string to compare against.`

**Return:**

- `bool`

---

md5(): static
-------------

[](#md5-static)

[↑](#voku-php-readme-class-methods)Create a md5 hash from the current string.

**Parameters:****nothing**

**Return:**

- `static`

---

newLineToHtmlBreak(): static
----------------------------

[](#newlinetohtmlbreak-static)

[↑](#voku-php-readme-class-methods)Replace all breaks \[
 | \\r\\n | \\r | \\n | ...\] into "
".

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

nth(int $step, int $offset): static
-----------------------------------

[](#nthint-step-int-offset-static)

[↑](#voku-php-readme-class-methods)Get every nth character of the string.

EXAMPLE: ``

**Parameters:**

- `int $step The number of characters to step.`
- `int $offset [optional] The string offset to start at.`

**Return:**

- `static`

---

offsetExists(int $offset): bool
-------------------------------

[](#offsetexistsint-offset-bool)

[↑](#voku-php-readme-class-methods)Returns whether or not a character exists at an index. Offsets may be negative to count from the last character in the string. Implements part of the ArrayAccess interface.

EXAMPLE: ``

**Parameters:**

- `int $offset The index to check.`

**Return:**

- `bool Whether or not the index exists.`

---

offsetGet(int $offset): string
------------------------------

[](#offsetgetint-offset-string)

[↑](#voku-php-readme-class-methods)Returns the character at the given index. Offsets may be negative to count from the last character in the string. Implements part of the ArrayAccess interface, and throws an OutOfBoundsException if the index does not exist.

EXAMPLE: ``

**Parameters:**

- `int $offset The index from which to retrieve the char.`

**Return:**

- `string The character at the specified index.`

---

offsetSet(int $offset, mixed $value): void
------------------------------------------

[](#offsetsetint-offset-mixed-value-void)

[↑](#voku-php-readme-class-methods)Implements part of the ArrayAccess interface, but throws an exception when called. This maintains the immutability of Stringy objects.

EXAMPLE: ``

**Parameters:**

- `int $offset The index of the character.`
- `mixed $value Value to set.`

**Return:**

- `void`

---

offsetUnset(int $offset): void
------------------------------

[](#offsetunsetint-offset-void)

[↑](#voku-php-readme-class-methods)Implements part of the ArrayAccess interface, but throws an exception when called. This maintains the immutability of Stringy objects.

EXAMPLE: ``

**Parameters:**

- `int $offset The index of the character.`

**Return:**

- `void`

---

pad(int $length, string $padStr, string $padType): static
---------------------------------------------------------

[](#padint-length-string-padstr-string-padtype-static)

[↑](#voku-php-readme-class-methods)Pads the string to a given length with $padStr. If length is less than or equal to the length of the string, no padding takes places. The default string used for padding is a space, and the default type (one of 'left', 'right', 'both') is 'right'. Throws an InvalidArgumentException if $padType isn't one of those 3 values.

EXAMPLE: `s('fòôbàř')->pad(9, '-/', 'left'); // '-/-fòôbàř'`

**Parameters:**

- `int $length Desired string length after padding.`
- `string $padStr [optional] String used to pad, defaults to space. Default: ' '`
- `string $padType [optional] One of 'left', 'right', 'both'. Default: 'right'`

**Return:**

- `static Object with a padded $str.`

---

padBoth(int $length, string $padStr): static
--------------------------------------------

[](#padbothint-length-string-padstr-static)

[↑](#voku-php-readme-class-methods)Returns a new string of a given length such that both sides of the string are padded. Alias for pad() with a $padType of 'both'.

EXAMPLE: `s('foo bar')->padBoth(9, ' '); // ' foo bar '`

**Parameters:**

- `int $length Desired string length after padding.`
- `string $padStr [optional] String used to pad, defaults to space. Default: ' '`

**Return:**

- `static String with padding applied.`

---

padLeft(int $length, string $padStr): static
--------------------------------------------

[](#padleftint-length-string-padstr-static)

[↑](#voku-php-readme-class-methods)Returns a new string of a given length such that the beginning of the string is padded. Alias for pad() with a $padType of 'left'.

EXAMPLE: `s('foo bar')->padLeft(9, ' '); // '  foo bar'`

**Parameters:**

- `int $length Desired string length after padding.`
- `string $padStr [optional] String used to pad, defaults to space. Default: ' '`

**Return:**

- `static String with left padding.`

---

padRight(int $length, string $padStr): static
---------------------------------------------

[](#padrightint-length-string-padstr-static)

[↑](#voku-php-readme-class-methods)Returns a new string of a given length such that the end of the string is padded. Alias for pad() with a $padType of 'right'.

EXAMPLE: `s('foo bar')->padRight(10, '*'); // 'foo bar*_'`

**Parameters:**

- `int $length Desired string length after padding.`
- `string $padStr [optional] String used to pad, defaults to space. Default: ' '`

**Return:**

- `static String with right padding.`

---

pascalCase(): static
--------------------

[](#pascalcase-static)

[↑](#voku-php-readme-class-methods)Convert the string to PascalCase.

Alias for studlyCase()

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

prepend(string $prefix): static
-------------------------------

[](#prependstring-prefix-static)

[↑](#voku-php-readme-class-methods)Returns a new string starting with $prefix.

EXAMPLE: `s('bàř')->prepend('fòô'); // 'fòôbàř'`

**Parameters:**

- `string ...$prefix The string to append.`

**Return:**

- `static Object with appended $prefix.`

---

prependStringy(\\CollectionStringy|static $prefix): static
----------------------------------------------------------

[](#prependstringycollectionstringystatic-prefix-static)

[↑](#voku-php-readme-class-methods)Returns a new string starting with $prefix.

EXAMPLE: ``

**Parameters:**

- `CollectionStringy|static ...$prefix The Stringy objects to append.`

**Return:**

- `static Object with appended $prefix.`

---

regexReplace(string $pattern, string $replacement, string $options, string $delimiter): static
----------------------------------------------------------------------------------------------

[](#regexreplacestring-pattern-string-replacement-string-options-string-delimiter-static)

[↑](#voku-php-readme-class-methods)Replaces all occurrences of $pattern in $str by $replacement.

EXAMPLE: `s('fòô ')->regexReplace('f[òô]+\s', 'bàř'); // 'bàř's('fò')->regexReplace('(ò)', '\1ô'); // 'fòô'`

**Parameters:**

- `string $pattern The regular expression pattern.`
- `string $replacement The string to replace with.`
- `string $options [optional] Matching conditions to be used.`
- `string $delimiter [optional] Delimiter the the regex. Default: '/'`

**Return:**

- `static Object with the result2ing $str after the replacements.`

---

removeHtml(string $allowableTags): static
-----------------------------------------

[](#removehtmlstring-allowabletags-static)

[↑](#voku-php-readme-class-methods)Remove html via "strip\_tags()" from the string.

EXAMPLE: `s('řàb òf', ôfoo lall')->removeHtml(''); // 'řàb òf', ôfoo lall'`

**Parameters:**

- `string $allowableTags \[optional\] You can use the optional second parameter to specify tags which should not be stripped. Default: null

` **Return:**

- `static`

---

removeHtmlBreak(string $replacement): static
--------------------------------------------

[](#removehtmlbreakstring-replacement-static)

[↑](#voku-php-readme-class-methods)Remove all breaks \[
 | \\r\\n | \\r | \\n | ...\] from the string.

EXAMPLE: `s('řàb òf', ôfoo lall')->removeHtmlBreak(''); // 'řàb òf', ô< foo lall'`

**Parameters:**

- `string $replacement [optional] Default is a empty string.`

**Return:**

- `static`

---

removeLeft(string $substring): static
-------------------------------------

[](#removeleftstring-substring-static)

[↑](#voku-php-readme-class-methods)Returns a new string with the prefix $substring removed, if present.

EXAMPLE: `s('fòôbàř')->removeLeft('fòô'); // 'bàř'`

**Parameters:**

- `string $substring The prefix to remove.`

**Return:**

- `static Object having a $str without the prefix $substring.`

---

removeRight(string $substring): static
--------------------------------------

[](#removerightstring-substring-static)

[↑](#voku-php-readme-class-methods)Returns a new string with the suffix $substring removed, if present.

EXAMPLE: `s('fòôbàř')->removeRight('bàř'); // 'fòô'`

**Parameters:**

- `string $substring The suffix to remove.`

**Return:**

- `static Object having a $str without the suffix $substring.`

---

removeXss(): static
-------------------

[](#removexss-static)

[↑](#voku-php-readme-class-methods)Try to remove all XSS-attacks from the string.

EXAMPLE: `s('')->removeXss(); // ''`

**Parameters:****nothing**

**Return:**

- `static`

---

repeat(int $multiplier): static
-------------------------------

[](#repeatint-multiplier-static)

[↑](#voku-php-readme-class-methods)Returns a repeated string given a multiplier.

EXAMPLE: `s('α')->repeat(3); // 'ααα'`

**Parameters:**

- `int $multiplier The number of times to repeat the string.`

**Return:**

- `static Object with a repeated str.`

---

replace(string $search, string $replacement, bool $caseSensitive): static
-------------------------------------------------------------------------

[](#replacestring-search-string-replacement-bool-casesensitive-static)

[↑](#voku-php-readme-class-methods)Replaces all occurrences of $search in $str by $replacement.

EXAMPLE: `s('fòô bàř fòô bàř')->replace('fòô ', ''); // 'bàř bàř'`

**Parameters:**

- `string $search The needle to search for.`
- `string $replacement The string to replace with.`
- `bool $caseSensitive [optional] Whether or not to enforce case-sensitivity. Default: true`

**Return:**

- `static Object with the resulting $str after the replacements.`

---

replaceAll(string\[\] $search, string|string\[\] $replacement, bool $caseSensitive): static
-------------------------------------------------------------------------------------------

[](#replaceallstring-search-stringstring-replacement-bool-casesensitive-static)

[↑](#voku-php-readme-class-methods)Replaces all occurrences of $search in $str by $replacement.

EXAMPLE: `s('fòô bàř lall bàř')->replaceAll(['fòÔ ', 'lall'], '', false); // 'bàř bàř'`

**Parameters:**

- `string[] $search The elements to search for.`
- `string|string[] $replacement The string to replace with.`
- `bool $caseSensitive [optional] Whether or not to enforce case-sensitivity. Default: true`

**Return:**

- `static Object with the resulting $str after the replacements.`

---

replaceBeginning(string $search, string $replacement): static
-------------------------------------------------------------

[](#replacebeginningstring-search-string-replacement-static)

[↑](#voku-php-readme-class-methods)Replaces all occurrences of $search from the beginning of string with $replacement.

EXAMPLE: `s('fòô bàř fòô bàř')->replaceBeginning('fòô', ''); // ' bàř bàř'`

**Parameters:**

- `string $search The string to search for.`
- `string $replacement The replacement.`

**Return:**

- `static Object with the resulting $str after the replacements.`

---

replaceEnding(string $search, string $replacement): static
----------------------------------------------------------

[](#replaceendingstring-search-string-replacement-static)

[↑](#voku-php-readme-class-methods)Replaces all occurrences of $search from the ending of string with $replacement.

EXAMPLE: `s('fòô bàř fòô bàř')->replaceEnding('bàř', ''); // 'fòô bàř fòô '`

**Parameters:**

- `string $search The string to search for.`
- `string $replacement The replacement.`

**Return:**

- `static Object with the resulting $str after the replacements.`

---

replaceFirst(string $search, string $replacement): static
---------------------------------------------------------

[](#replacefirststring-search-string-replacement-static)

[↑](#voku-php-readme-class-methods)Replaces first occurrences of $search from the beginning of string with $replacement.

EXAMPLE: ``

**Parameters:**

- `string $search The string to search for.`
- `string $replacement The replacement.`

**Return:**

- `static Object with the resulting $str after the replacements.`

---

replaceLast(string $search, string $replacement): static
--------------------------------------------------------

[](#replacelaststring-search-string-replacement-static)

[↑](#voku-php-readme-class-methods)Replaces last occurrences of $search from the ending of string with $replacement.

EXAMPLE: ``

**Parameters:**

- `string $search The string to search for.`
- `string $replacement The replacement.`

**Return:**

- `static Object with the resulting $str after the replacements.`

---

reverse(): static
-----------------

[](#reverse-static)

[↑](#voku-php-readme-class-methods)Returns a reversed string. A multibyte version of strrev().

EXAMPLE: `s('fòôbàř')->reverse(); // 'řàbôòf'`

**Parameters:****nothing**

**Return:**

- `static Object with a reversed $str.`

---

safeTruncate(int $length, string $substring, bool $ignoreDoNotSplitWordsForOneWord): static
-------------------------------------------------------------------------------------------

[](#safetruncateint-length-string-substring-bool-ignoredonotsplitwordsforoneword-static)

[↑](#voku-php-readme-class-methods)Truncates the string to a given length, while ensuring that it does not split words. If $substring is provided, and truncating occurs, the string is further truncated so that the substring may be appended without exceeding the desired length.

EXAMPLE: `s('What are your plans today?')->safeTruncate(22, '...'); // 'What are your plans...'`

**Parameters:**

- `int $length Desired length of the truncated string.`
- `string $substring [optional] The substring to append if it can fit. Default: ''`
- `bool $ignoreDoNotSplitWordsForOneWord`

**Return:**

- `static Object with the resulting $str after truncating.`

---

setInternalEncoding(string $new\_encoding): static
--------------------------------------------------

[](#setinternalencodingstring-new_encoding-static)

[↑](#voku-php-readme-class-methods)Set the internal character encoding.

EXAMPLE: ``

**Parameters:**

- `string $new_encoding The desired character encoding.`

**Return:**

- `static`

---

sha1(): static
--------------

[](#sha1-static)

[↑](#voku-php-readme-class-methods)Create a sha1 hash from the current string.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

sha256(): static
----------------

[](#sha256-static)

[↑](#voku-php-readme-class-methods)Create a sha256 hash from the current string.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

sha512(): static
----------------

[](#sha512-static)

[↑](#voku-php-readme-class-methods)Create a sha512 hash from the current string.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

shortenAfterWord(int $length, string $strAddOn): static
-------------------------------------------------------

[](#shortenafterwordint-length-string-straddon-static)

[↑](#voku-php-readme-class-methods)Shorten the string after $length, but also after the next word.

EXAMPLE: `s('this is a test')->shortenAfterWord(2, '...'); // 'this...'`

**Parameters:**

- `int $length The given length.`
- `string $strAddOn [optional] Default: '…'`

**Return:**

- `static`

---

shuffle(): static
-----------------

[](#shuffle-static)

[↑](#voku-php-readme-class-methods)A multibyte string shuffle function. It returns a string with its characters in random order.

EXAMPLE: `s('fòôbàř')->shuffle(); // 'àôřbòf'`

**Parameters:****nothing**

**Return:**

- `static Object with a shuffled $str.`

---

similarity(string $str): float
------------------------------

[](#similaritystring-str-float)

[↑](#voku-php-readme-class-methods)Calculate the similarity between two strings.

EXAMPLE: ``

**Parameters:**

- `string $str The delimiting string.`

**Return:**

- `float`

---

slice(int $start, int $end): static
-----------------------------------

[](#sliceint-start-int-end-static)

[↑](#voku-php-readme-class-methods)Returns the substring beginning at $start, and up to, but not including the index specified by $end. If $end is omitted, the function extracts the remaining string. If $end is negative, it is computed from the end of the string.

EXAMPLE: `s('fòôbàř')->slice(3, -1); // 'bà'`

**Parameters:**

- `int $start Initial index from which to begin extraction.`
- `int $end [optional] Index at which to end extraction. Default: null`

**Return:**

- `static Object with its $str being the extracted substring.`

---

slugify(string $separator, string $language, string\[\] $replacements, bool $replace\_extra\_symbols, bool $use\_str\_to\_lower, bool $use\_transliterate): static
------------------------------------------------------------------------------------------------------------------------------------------------------------------

[](#slugifystring-separator-string-language-string-replacements-bool-replace_extra_symbols-bool-use_str_to_lower-bool-use_transliterate-static)

[↑](#voku-php-readme-class-methods)Converts the string into an URL slug. This includes replacing non-ASCII characters with their closest ASCII equivalents, removing remaining non-ASCII and non-alphanumeric characters, and replacing whitespace with $separator. The separator defaults to a single dash, and the string is also converted to lowercase. The language of the source string can also be supplied for language-specific transliteration.

EXAMPLE: `s('Using strings like fòô bàř')->slugify(); // 'using-strings-like-foo-bar'`

**Parameters:**

- `string $separator [optional] The string used to replace whitespace.`
- `ASCII::*_LANGUAGE_CODE $language [optional] Language of the source string.`
- `array $replacements [optional] A map of replaceable strings.`
- `bool $replace_extra_symbols [optional]  Add some more replacements e.g. "£" with " pound ".`
- `bool $use_str_to_lower [optional] Use "string to lower" for the input.`
- `bool $use_transliterate [optional]  Use ASCII::to_transliterate() for unknown chars.`

**Return:**

- `static Object whose $str has been converted to an URL slug.`

---

snakeCase(): static
-------------------

[](#snakecase-static)

[↑](#voku-php-readme-class-methods)Convert the string to snake\_case.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

snakeize(): static
------------------

[](#snakeize-static)

[↑](#voku-php-readme-class-methods)Convert a string to snake\_case.

EXAMPLE: `s('foo1 Bar')->snakeize(); // 'foo_1_bar'`

**Parameters:****nothing**

**Return:**

- `static Object with $str in snake_case.`

---

softWrap(int $width, string $break): static
-------------------------------------------

[](#softwrapint-width-string-break-static)

[↑](#voku-php-readme-class-methods)Wrap the string after the first whitespace character after a given number of characters.

EXAMPLE: ``

**Parameters:**

- `int $width Number of characters at which to wrap.`
- `string $break [optional] Character used to break the string. | Default "\n"`

**Return:**

- `static`

---

split(string $pattern, int $limit): static\[\]
----------------------------------------------

[](#splitstring-pattern-int-limit-static)

[↑](#voku-php-readme-class-methods)Splits the string with the provided regular expression, returning an array of Stringy objects. An optional integer $limit will truncate the results.

EXAMPLE: `s('foo,bar,baz')->split(',', 2); // ['foo', 'bar']`

**Parameters:**

- `string $pattern The regex with which to split the string.`
- `int $limit [optional] Maximum number of results to return. Default: -1 === no limit`

**Return:**

- `static[] An array of Stringy objects.`

---

splitCollection(string $pattern, int $limit): CollectionStringy|static\[\]
--------------------------------------------------------------------------

[](#splitcollectionstring-pattern-int-limit-collectionstringystatic)

[↑](#voku-php-readme-class-methods)Splits the string with the provided regular expression, returning an collection of Stringy objects. An optional integer $limit will truncate the results.

EXAMPLE: ``

**Parameters:**

- `string $pattern The regex with which to split the string.`
- `int $limit [optional] Maximum number of results to return. Default: -1 === no limit`

**Return:**

- `\CollectionStringy|static[] An collection of Stringy objects.`

---

startsWith(string $substring, bool $caseSensitive): bool
--------------------------------------------------------

[](#startswithstring-substring-bool-casesensitive-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string begins with $substring, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.

EXAMPLE: `s('FÒÔbàřbaz')->startsWith('fòôbàř', false); // true`

**Parameters:**

- `string $substring The substring to look for.`
- `bool $caseSensitive [optional] Whether or not to enforce case-sensitivity. Default: true`

**Return:**

- `bool Whether or not $str starts with $substring.`

---

startsWithAny(string\[\] $substrings, bool $caseSensitive): bool
----------------------------------------------------------------

[](#startswithanystring-substrings-bool-casesensitive-bool)

[↑](#voku-php-readme-class-methods)Returns true if the string begins with any of $substrings, false otherwise.

By default the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.

EXAMPLE: `s('FÒÔbàřbaz')->startsWithAny(['fòô', 'bàř'], false); // true`

**Parameters:**

- `string[] $substrings Substrings to look for.`
- `bool $caseSensitive [optional] Whether or not to enforce case-sensitivity. Default: true`

**Return:**

- `bool Whether or not $str starts with $substring.`

---

strip(string|string\[\] $search): static
----------------------------------------

[](#stripstringstring-search-static)

[↑](#voku-php-readme-class-methods)Remove one or more strings from the string.

EXAMPLE: ``

**Parameters:**

- `string|string[] $search One or more strings to be removed`

**Return:**

- `static`

---

stripWhitespace(): static
-------------------------

[](#stripwhitespace-static)

[↑](#voku-php-readme-class-methods)Strip all whitespace characters. This includes tabs and newline characters, as well as multibyte whitespace such as the thin space and ideographic space.

EXAMPLE: `s('   Ο     συγγραφέας  ')->stripWhitespace(); // 'Οσυγγραφέας'`

**Parameters:****nothing**

**Return:**

- `static`

---

stripeCssMediaQueries(): static
-------------------------------

[](#stripecssmediaqueries-static)

[↑](#voku-php-readme-class-methods)Remove css media-queries.

EXAMPLE: `s('test @media (min-width:660px){ .des-cla #mv-tiles{width:480px} } test ')->stripeCssMediaQueries(); // 'test  test '`

**Parameters:****nothing**

**Return:**

- `static`

---

stripeEmptyHtmlTags(): static
-----------------------------

[](#stripeemptyhtmltags-static)

[↑](#voku-php-readme-class-methods)Remove empty html-tag.

EXAMPLE: `s('foo`

`bar')->stripeEmptyHtmlTags(); // 'foobar'`**Parameters:****nothing**

**Return:**

- `static`

---

studlyCase(): static
--------------------

[](#studlycase-static)

[↑](#voku-php-readme-class-methods)Convert the string to StudlyCase.

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

substr(int $start, int $length): static
---------------------------------------

[](#substrint-start-int-length-static)

[↑](#voku-php-readme-class-methods)Returns the substring beginning at $start with the specified $length.

It differs from the $this-&gt;utf8::substr() function in that providing a $length of null will return the rest of the string, rather than an empty string.

EXAMPLE: ``

**Parameters:**

- `int $start Position of the first character to use.`
- `int $length [optional] Maximum number of characters used. Default: null`

**Return:**

- `static Object with its $str being the substring.`

---

substring(int $start, int $length): static
------------------------------------------

[](#substringint-start-int-length-static)

[↑](#voku-php-readme-class-methods)Return part of the string.

Alias for substr()

EXAMPLE: `s('fòôbàř')->substring(2, 3); // 'ôbà'`

**Parameters:**

- `int $start Starting position of the substring.`
- `int $length [optional] Length of substring.`

**Return:**

- `static`

---

substringOf(string $needle, bool $beforeNeedle): static
-------------------------------------------------------

[](#substringofstring-needle-bool-beforeneedle-static)

[↑](#voku-php-readme-class-methods)Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".

If no match is found returns new empty Stringy object.

EXAMPLE: ``

**Parameters:**

- `string $needle The string to look for.`
- `bool $beforeNeedle [optional] Default: false`

**Return:**

- `static`

---

substringOfIgnoreCase(string $needle, bool $beforeNeedle): static
-----------------------------------------------------------------

[](#substringofignorecasestring-needle-bool-beforeneedle-static)

[↑](#voku-php-readme-class-methods)Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".

If no match is found returns new empty Stringy object.

EXAMPLE: ``

**Parameters:**

- `string $needle The string to look for.`
- `bool $beforeNeedle [optional] Default: false`

**Return:**

- `static`

---

surround(string $substring): static
-----------------------------------

[](#surroundstring-substring-static)

[↑](#voku-php-readme-class-methods)Surrounds $str with the given substring.

EXAMPLE: `s(' ͜ ')->surround('ʘ'); // 'ʘ ͜ ʘ'`

**Parameters:**

- `string $substring The substring to add to both sides.`

**Return:**

- `static Object whose $str had the substring both prepended and appended.`

---

swapCase(): static
------------------

[](#swapcase-static)

[↑](#voku-php-readme-class-methods)Returns a case swapped version of the string.

EXAMPLE: `s('Ντανιλ')->swapCase(); // 'νΤΑΝΙΛ'`

**Parameters:****nothing**

**Return:**

- `static Object whose $str has each character's case swapped.`

---

tidy(): static
--------------

[](#tidy-static)

[↑](#voku-php-readme-class-methods)Returns a string with smart quotes, ellipsis characters, and dashes from Windows-1252 (commonly used in Word documents) replaced by their ASCII equivalents.

EXAMPLE: `s('“I see…”')->tidy(); // '"I see..."'`

**Parameters:****nothing**

**Return:**

- `static Object whose $str has those characters removed.`

---

titleize(string\[\]|null $ignore, string|null $word\_define\_chars, string|null $language): static
--------------------------------------------------------------------------------------------------

[](#titleizestringnull-ignore-stringnull-word_define_chars-stringnull-language-static)

[↑](#voku-php-readme-class-methods)Returns a trimmed string with the first letter of each word capitalized.

Also accepts an array, $ignore, allowing you to list words not to be capitalized.

EXAMPLE: `$ignore = ['at', 'by', 'for', 'in', 'of', 'on', 'out', 'to', 'the'];s('i like to watch television')->titleize($ignore); // 'I Like to Watch Television'`

**Parameters:**

- `string[]|null $ignore [optional] An array of words not to capitalize or null. Default: null`
- `string|null $word_define_chars [optional] An string of chars that will be used as whitespace separator === words.`
- `string|null $language [optional] Language of the source string.`

**Return:**

- `static Object with a titleized $str.`

---

titleizeForHumans(string\[\] $ignore): static
---------------------------------------------

[](#titleizeforhumansstring-ignore-static)

[↑](#voku-php-readme-class-methods)Returns a trimmed string in proper title case: Also accepts an array, $ignore, allowing you to list words not to be capitalized.

EXAMPLE: ``

Adapted from John Gruber's script.

**Parameters:**

- `string[] $ignore An array of words not to capitalize.`

**Return:**

- `static Object with a titleized $str`

---

toAscii(string $language, bool $removeUnsupported): static
----------------------------------------------------------

[](#toasciistring-language-bool-removeunsupported-static)

[↑](#voku-php-readme-class-methods)Returns an ASCII version of the string. A set of non-ASCII characters are replaced with their closest ASCII counterparts, and the rest are removed by default. The language or locale of the source string can be supplied for language-specific transliteration in any of the following formats: en, en\_GB, or en-GB. For example, passing "de" results in "äöü" mapping to "aeoeue" rather than "aou" as in other languages.

EXAMPLE: `s('fòôbàř')->toAscii(); // 'foobar'`

**Parameters:**

- `ASCII::*_LANGUAGE_CODE $language [optional] Language of the source string.`
- `bool $removeUnsupported [optional] Whether or not to remove the unsupported characters.`

**Return:**

- `static Object whose $str contains only ASCII characters.`

---

toBoolean(): bool
-----------------

[](#toboolean-bool)

[↑](#voku-php-readme-class-methods)Returns a boolean representation of the given logical string value.

For example, **'true', '1', 'on' and 'yes'** will return true. **'false', '0', 'off', and 'no'** will return false. In all instances, case is ignored. For other numeric strings, their sign will determine the return value. In addition, blank strings consisting of only whitespace will return false. For all other strings, the return value is a result of a boolean cast.

EXAMPLE: `s('OFF')->toBoolean(); // false`

**Parameters:****nothing**

**Return:**

- `bool A boolean value for the string.`

---

toLowerCase(bool $tryToKeepStringLength, string|null $lang): static
-------------------------------------------------------------------

[](#tolowercasebool-trytokeepstringlength-stringnull-lang-static)

[↑](#voku-php-readme-class-methods)Converts all characters in the string to lowercase.

EXAMPLE: `s('FÒÔBÀŘ')->toLowerCase(); // 'fòôbàř'`

**Parameters:**

- `bool $tryToKeepStringLength [optional] true === try to keep the string length: e.g. ẞ -> ß`
- `string|null $lang [optional] Set the language for special cases: az, el, lt, tr`

**Return:**

- `static Object with all characters of $str being lowercase.`

---

toSpaces(int $tabLength): static
--------------------------------

[](#tospacesint-tablength-static)

[↑](#voku-php-readme-class-methods)Converts each tab in the string to some number of spaces, as defined by $tabLength. By default, each tab is converted to 4 consecutive spaces.

EXAMPLE: `s(' String speech = "Hi"')->toSpaces(); // '    String speech = "Hi"'`

**Parameters:**

- `int $tabLength [optional] Number of spaces to replace each tab with. Default: 4`

**Return:**

- `static Object whose $str has had tabs switched to spaces.`

---

toString(): string
------------------

[](#tostring-string)

[↑](#voku-php-readme-class-methods)Return Stringy object as string, but you can also use (string) for automatically casting the object into a string.

EXAMPLE: `s('fòôbàř')->toString(); // 'fòôbàř'`

**Parameters:****nothing**

**Return:**

- `string`

---

toTabs(int $tabLength): static
------------------------------

[](#totabsint-tablength-static)

[↑](#voku-php-readme-class-methods)Converts each occurrence of some consecutive number of spaces, as defined by $tabLength, to a tab. By default, each 4 consecutive spaces are converted to a tab.

EXAMPLE: `s('    fòô    bàř')->toTabs(); // '   fòô bàř'`

**Parameters:**

- `int $tabLength [optional] Number of spaces to replace with a tab. Default: 4`

**Return:**

- `static Object whose $str has had spaces switched to tabs.`

---

toTitleCase(): static
---------------------

[](#totitlecase-static)

[↑](#voku-php-readme-class-methods)Converts the first character of each word in the string to uppercase and all other chars to lowercase.

EXAMPLE: `s('fòô bàř')->toTitleCase(); // 'Fòô Bàř'`

**Parameters:****nothing**

**Return:**

- `static Object with all characters of $str being title-cased.`

---

toTransliterate(bool $strict, string $unknown): static
------------------------------------------------------

[](#totransliteratebool-strict-string-unknown-static)

[↑](#voku-php-readme-class-methods)Returns an ASCII version of the string. A set of non-ASCII characters are replaced with their closest ASCII counterparts, and the rest are removed unless instructed otherwise.

EXAMPLE: ``

**Parameters:**

- `bool $strict [optional] Use "transliterator_transliterate()" from PHP-Intl | WARNING: bad performance | Default: false`
- `string $unknown [optional] Character use if character unknown. (default is ?)`

**Return:**

- `static Object whose $str contains only ASCII characters.`

---

toUpperCase(bool $tryToKeepStringLength, string|null $lang): static
-------------------------------------------------------------------

[](#touppercasebool-trytokeepstringlength-stringnull-lang-static)

[↑](#voku-php-readme-class-methods)Converts all characters in the string to uppercase.

EXAMPLE: `s('fòôbàř')->toUpperCase(); // 'FÒÔBÀŘ'`

**Parameters:**

- `bool $tryToKeepStringLength [optional] true === try to keep the string length: e.g. ẞ -> ß`
- `string|null $lang [optional] Set the language for special cases: az, el, lt, tr`

**Return:**

- `static Object with all characters of $str being uppercase.`

---

trim(string $chars): static
---------------------------

[](#trimstring-chars-static)

[↑](#voku-php-readme-class-methods)Returns a string with whitespace removed from the start and end of the string. Supports the removal of unicode whitespace. Accepts an optional string of characters to strip instead of the defaults.

EXAMPLE: `s('  fòôbàř  ')->trim(); // 'fòôbàř'`

**Parameters:**

- `string $chars [optional] String of characters to strip. Default: null`

**Return:**

- `static Object with a trimmed $str.`

---

trimLeft(string $chars): static
-------------------------------

[](#trimleftstring-chars-static)

[↑](#voku-php-readme-class-methods)Returns a string with whitespace removed from the start of the string.

Supports the removal of unicode whitespace. Accepts an optional string of characters to strip instead of the defaults.

EXAMPLE: `s('  fòôbàř  ')->trimLeft(); // 'fòôbàř  '`

**Parameters:**

- `string $chars [optional] Optional string of characters to strip. Default: null`

**Return:**

- `static Object with a trimmed $str.`

---

trimRight(string $chars): static
--------------------------------

[](#trimrightstring-chars-static)

[↑](#voku-php-readme-class-methods)Returns a string with whitespace removed from the end of the string.

Supports the removal of unicode whitespace. Accepts an optional string of characters to strip instead of the defaults.

EXAMPLE: `s('  fòôbàř  ')->trimRight(); // '  fòôbàř'`

**Parameters:**

- `string $chars [optional] Optional string of characters to strip. Default: null`

**Return:**

- `static Object with a trimmed $str.`

---

truncate(int $length, string $substring): static
------------------------------------------------

[](#truncateint-length-string-substring-static)

[↑](#voku-php-readme-class-methods)Truncates the string to a given length. If $substring is provided, and truncating occurs, the string is further truncated so that the substring may be appended without exceeding the desired length.

EXAMPLE: `s('What are your plans today?')->truncate(19, '...'); // 'What are your pl...'`

**Parameters:**

- `int $length Desired length of the truncated string.`
- `string $substring [optional] The substring to append if it can fit. Default: ''`

**Return:**

- `static Object with the resulting $str after truncating.`

---

underscored(): static
---------------------

[](#underscored-static)

[↑](#voku-php-readme-class-methods)Returns a lowercase and trimmed string separated by underscores.

Underscores are inserted before uppercase characters (with the exception of the first character of the string), and in place of spaces as well as dashes.

EXAMPLE: `s('TestUCase')->underscored(); // 'test_u_case'`

**Parameters:****nothing**

**Return:**

- `static Object with an underscored $str.`

---

upperCamelize(): static
-----------------------

[](#uppercamelize-static)

[↑](#voku-php-readme-class-methods)Returns an UpperCamelCase version of the supplied string. It trims surrounding spaces, capitalizes letters following digits, spaces, dashes and underscores, and removes spaces, dashes, underscores.

EXAMPLE: `s('Upper Camel-Case')->upperCamelize(); // 'UpperCamelCase'`

**Parameters:****nothing**

**Return:**

- `static Object with $str in UpperCamelCase.`

---

upperCaseFirst(): static
------------------------

[](#uppercasefirst-static)

[↑](#voku-php-readme-class-methods)Converts the first character of the supplied string to upper case.

EXAMPLE: `s('σ foo')->upperCaseFirst(); // 'Σ foo'`

**Parameters:****nothing**

**Return:**

- `static Object with the first character of $str being upper case.`

---

urlDecode(): static
-------------------

[](#urldecode-static)

[↑](#voku-php-readme-class-methods)Simple url-decoding.

e.g: 'test+test' =&gt; 'test test'

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

urlDecodeMulti(): static
------------------------

[](#urldecodemulti-static)

[↑](#voku-php-readme-class-methods)Multi url-decoding + decode HTML entity + fix urlencoded-win1252-chars.

e.g: 'test+test' =&gt; 'test test' 'Düsseldorf' =&gt; 'Düsseldorf' 'D%FCsseldorf' =&gt; 'Düsseldorf' 'Düsseldorf' =&gt; 'Düsseldorf' 'D%26%23xFC%3Bsseldorf' =&gt; 'Düsseldorf' 'DÃ¼sseldorf' =&gt; 'Düsseldorf' 'D%C3%BCsseldorf' =&gt; 'Düsseldorf' 'D%C3%83%C2%BCsseldorf' =&gt; 'Düsseldorf' 'D%25C3%2583%25C2%25BCsseldorf' =&gt; 'Düsseldorf'

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

urlDecodeRaw(): static
----------------------

[](#urldecoderaw-static)

[↑](#voku-php-readme-class-methods)Simple url-decoding.

e.g: 'test+test' =&gt; 'test+test

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

urlDecodeRawMulti(): static
---------------------------

[](#urldecoderawmulti-static)

[↑](#voku-php-readme-class-methods)Multi url-decoding + decode HTML entity + fix urlencoded-win1252-chars.

e.g: 'test+test' =&gt; 'test+test' 'Düsseldorf' =&gt; 'Düsseldorf' 'D%FCsseldorf' =&gt; 'Düsseldorf' 'Düsseldorf' =&gt; 'Düsseldorf' 'D%26%23xFC%3Bsseldorf' =&gt; 'Düsseldorf' 'DÃ¼sseldorf' =&gt; 'Düsseldorf' 'D%C3%BCsseldorf' =&gt; 'Düsseldorf' 'D%C3%83%C2%BCsseldorf' =&gt; 'Düsseldorf' 'D%25C3%2583%25C2%25BCsseldorf' =&gt; 'Düsseldorf'

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

urlEncode(): static
-------------------

[](#urlencode-static)

[↑](#voku-php-readme-class-methods)Simple url-encoding.

e.g: 'test test' =&gt; 'test+test'

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

urlEncodeRaw(): static
----------------------

[](#urlencoderaw-static)

[↑](#voku-php-readme-class-methods)Simple url-encoding.

e.g: 'test test' =&gt; 'test%20test'

EXAMPLE: ``

**Parameters:****nothing**

**Return:**

- `static`

---

urlify(string $separator, string $language, string\[\] $replacements, bool $strToLower): static
-----------------------------------------------------------------------------------------------

[](#urlifystring-separator-string-language-string-replacements-bool-strtolower-static)

[↑](#voku-php-readme-class-methods)Converts the string into an URL slug. This includes replacing non-ASCII characters with their closest ASCII equivalents, removing remaining non-ASCII and non-alphanumeric characters, and replacing whitespace with $separator. The separator defaults to a single dash, and the string is also converted to lowercase.

EXAMPLE: `s('Using strings like fòô bàř - 1$')->urlify(); // 'using-strings-like-foo-bar-1-dollar'`

**Parameters:**

- `string $separator [optional] The string used to replace whitespace. Default: '-'`
- `string $language [optional] The language for the url. Default: 'en'`
- `array $replacements [optional] A map of replaceable strings.`
- `bool $strToLower [optional] string to lower. Default: true`

**Return:**

- `static Object whose $str has been converted to an URL slug.`

---

utf8ify(): static
-----------------

[](#utf8ify-static)

[↑](#voku-php-readme-class-methods)Converts the string into an valid UTF-8 string.

EXAMPLE: `s('DÃ¼sseldorf')->utf8ify(); // 'Düsseldorf'`

**Parameters:****nothing**

**Return:**

- `static`

---

words(string $char\_list, bool $remove\_empty\_values, int|null $remove\_short\_values): static\[\]
---------------------------------------------------------------------------------------------------

[](#wordsstring-char_list-bool-remove_empty_values-intnull-remove_short_values-static)

[↑](#voku-php-readme-class-methods)Convert a string into an array of words.

EXAMPLE: ``

**Parameters:**

- `string $char_list [optional] Additional chars for the definition of "words".`
- `bool $remove_empty_values [optional] Remove empty values.`
- `int|null $remove_short_values [optional] The min. string length or null to disable`

**Return:**

- `static[]`

---

wordsCollection(string $char\_list, bool $remove\_empty\_values, int|null $remove\_short\_values): CollectionStringy|static\[\]
-------------------------------------------------------------------------------------------------------------------------------

[](#wordscollectionstring-char_list-bool-remove_empty_values-intnull-remove_short_values-collectionstringystatic)

[↑](#voku-php-readme-class-methods)Convert a string into an collection of words.

EXAMPLE: `S::create('中文空白 oöäü#s')->wordsCollection('#', true)->toStrings(); // ['中文空白', 'oöäü#s']`

**Parameters:**

- `string $char_list [optional] Additional chars for the definition of "words".`
- `bool $remove_empty_values [optional] Remove empty values.`
- `int|null $remove_short_values [optional] The min. string length or null to disable`

**Return:**

- `\CollectionStringy|static[] An collection of Stringy objects.`

---

wrap(string $substring): static
-------------------------------

[](#wrapstring-substring-static)

[↑](#voku-php-readme-class-methods)Surrounds $str with the given substring.

EXAMPLE: ``

**Parameters:**

- `string $substring The substring to add to both sides.`

**Return:**

- `static Object whose $str had the substring both prepended and appended.`

---

Tests
-----

[](#tests)

From the project directory, tests can be ran using `phpunit`

Support
-------

[](#support)

For support and donations please visit [GitHub](https://github.com/voku/Stringy/) | [Issues](https://github.com/voku/Stringy/issues) | [PayPal](https://paypal.me/moelleken) | [Patreon](https://www.patreon.com/voku).

For status updates and release announcements please visit [Releases](https://github.com/voku/Stringy/releases) | [Twitter](https://twitter.com/suckup_de) | [Patreon](https://www.patreon.com/voku/posts).

For professional support please contact [me](https://about.me/voku).

Thanks
------

[](#thanks)

- Thanks to [GitHub](https://github.com) (Microsoft) for hosting the code and a good infrastructure including Issues-Management, etc.
- Thanks to [IntelliJ](https://www.jetbrains.com) as they make the best IDEs for PHP and they gave me an open source license for PhpStorm!
- Thanks to [Travis CI](https://travis-ci.com/) for being the most awesome, easiest continuous integration tool out there!
- Thanks to [StyleCI](https://styleci.io/) for the simple but powerful code style check.
- Thanks to [PHPStan](https://github.com/phpstan/phpstan) &amp;&amp; [Psalm](https://github.com/vimeo/psalm) for really great Static analysis tools and for discover bugs in the code!

License
-------

[](#license)

Released under the MIT License - see `LICENSE.txt` for details.

###  Health Score

69

—

FairBetter than 100% of packages

Maintenance93

Actively maintained with recent releases

Popularity59

Moderate usage in the ecosystem

Community39

Small or concentrated contributor base

Maturity75

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~48 days

Recently: every ~386 days

Total

97

Last Release

47d ago

Major Versions

2.2.36 → 3.1.02017-06-12

3.0.0 → 4.0.02017-12-23

4.1.2 → 5.0.02019-01-11

5.2.0 → 6.0.02019-09-28

6.5.3 → 7.0.02026-04-22

PHP version history (4 changes)1.0.0-rc.1PHP &gt;=5.3.0

3.0.1PHP &gt;=5.4.0

3.0.0PHP &gt;=7.0.0

7.0.0PHP &gt;=7.1.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/6456fe693db197c458272cb758bf78958bc7d3e787ccd59db4bf3cf41654316a?d=identicon)[voku](/maintainers/voku)

---

Top Contributors

[![danielstjules](https://avatars.githubusercontent.com/u/817212?v=4)](https://github.com/danielstjules "danielstjules (226 commits)")[![voku](https://avatars.githubusercontent.com/u/264695?v=4)](https://github.com/voku "voku (210 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (39 commits)")[![vlakoff](https://avatars.githubusercontent.com/u/544424?v=4)](https://github.com/vlakoff "vlakoff (19 commits)")[![lucasmichot](https://avatars.githubusercontent.com/u/513603?v=4)](https://github.com/lucasmichot "lucasmichot (16 commits)")[![szepeviktor](https://avatars.githubusercontent.com/u/952007?v=4)](https://github.com/szepeviktor "szepeviktor (6 commits)")[![gotterdemarung](https://avatars.githubusercontent.com/u/2094324?v=4)](https://github.com/gotterdemarung "gotterdemarung (6 commits)")[![GrahamCampbell](https://avatars.githubusercontent.com/u/2829600?v=4)](https://github.com/GrahamCampbell "GrahamCampbell (5 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (2 commits)")[![Big-Shark](https://avatars.githubusercontent.com/u/646054?v=4)](https://github.com/Big-Shark "Big-Shark (2 commits)")[![maximal](https://avatars.githubusercontent.com/u/980679?v=4)](https://github.com/maximal "maximal (2 commits)")[![Bilge](https://avatars.githubusercontent.com/u/470626?v=4)](https://github.com/Bilge "Bilge (2 commits)")[![boboldehampsink](https://avatars.githubusercontent.com/u/378974?v=4)](https://github.com/boboldehampsink "boboldehampsink (2 commits)")[![badlamer](https://avatars.githubusercontent.com/u/1637293?v=4)](https://github.com/badlamer "badlamer (2 commits)")[![ChristianGaertner](https://avatars.githubusercontent.com/u/2886317?v=4)](https://github.com/ChristianGaertner "ChristianGaertner (2 commits)")[![jcroll](https://avatars.githubusercontent.com/u/1441013?v=4)](https://github.com/jcroll "jcroll (1 commits)")[![joshdifabio](https://avatars.githubusercontent.com/u/5609851?v=4)](https://github.com/joshdifabio "joshdifabio (1 commits)")[![kesselb](https://avatars.githubusercontent.com/u/3902676?v=4)](https://github.com/kesselb "kesselb (1 commits)")[![pborreli](https://avatars.githubusercontent.com/u/77759?v=4)](https://github.com/pborreli "pborreli (1 commits)")[![rugabarbo](https://avatars.githubusercontent.com/u/6429469?v=4)](https://github.com/rugabarbo "rugabarbo (1 commits)")

---

Tags

hacktoberfestphpphp7string-manipulationstringifyunicodeunicode-charactersutf-8stringutilityhelpersmanipulationmultibyteutilsUTFmethods

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/voku-stringy/health.svg)

```
[![Health](https://phpackages.com/badges/voku-stringy/health.svg)](https://phpackages.com/packages/voku-stringy)
```

###  Alternatives

[danielstjules/stringy

A string manipulation library with multibyte support

2.4k26.2M192](/packages/danielstjules-stringy)[statamic/stringy

A string manipulation library with multibyte support, forked from @statamic

244.8M17](/packages/statamic-stringy)[tcb13/substringy

A sub string manipulation library with multibyte support that extends Stringy

1760.9k1](/packages/tcb13-substringy)[voku/arrayy

Array manipulation library for PHP, called Arrayy!

4915.6M18](/packages/voku-arrayy)[nette/utils

🛠 Nette Utils: lightweight utilities for string &amp; array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.

2.2k417.9M1.6k](/packages/nette-utils)[voku/portable-utf8

Portable UTF-8 library - performance optimized (unicode) string functions for php.

52023.1M48](/packages/voku-portable-utf8)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
