PHPackages                             str/str - 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. str/str

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

str/str
=======

A fast modern string manipulation library with multibyte support. Based on Stringy, with focus on speed.

1.1.3(5y ago)18762.7k↓41.7%10[2 issues](https://github.com/fe3dback/str/issues)5MITPHPPHP &gt;=7.2.0

Since Feb 25Pushed 5y ago6 watchersCompare

[ Source](https://github.com/fe3dback/str)[ Packagist](https://packagist.org/packages/str/str)[ Docs](https://github.com/fe3dback/str)[ RSS](/packages/str-str/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (6)Dependencies (6)Versions (12)Used By (5)

About
-----

[](#about)

str/str
=======

[](#strstr)

[![Build Status](https://camo.githubusercontent.com/c0ca6bc76b3bced837966d7656aaf4c72a64321567f4612201c6833915e9129d/68747470733a2f2f7472617669732d63692e6f72672f666533646261636b2f7374722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/fe3dback/str)[![Coverage Status](https://camo.githubusercontent.com/cfc9aa754ca0745bdb71d81e1c34d90940f120853525d25f8642dd5448aec987/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f666533646261636b2f7374722f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/fe3dback/str?branch=master)[![BCH compliance](https://camo.githubusercontent.com/9c780c1b1137734634e235f06d3a8bc43258dc09a62354d150e572f423a38f37/68747470733a2f2f626574746572636f64656875622e636f6d2f656467652f62616467652f666533646261636b2f7374723f6272616e63683d6d6173746572)](https://bettercodehub.com/)

```
$str = new Str('Hello, 世界');
$str->last(2); // 世界
$str->chars(); // ['世', '界']

$str
    ->ensureLeft('Hello, ') // Hello, 世界
    ->ensureRight('!!!') // Hello, 世界!!!
    ->trimRight('!') // Hello, 世界
    ->prepend('Str say - '); // Str say - Hello, 世界

$send = function (string $s) {};
$send((string)$str); // same
$send($str->getString()); // same
```

---

Install
-------

[](#install)

**Requirements**:

- php7.1

```
composer require str/str
```

Features
--------

[](#features)

- strongly typed
- no exceptions thrown
- fast
- new functions

A fast string manipulation library with multi-byte support. Inspired by the ["Stringy"](https://github.com/danielstjules/Stringy) library, with focus on speed.

Lib uses php7 features and does not throw any exceptions (because all input parameters are strongly typed). The code is completely covered by unit tests.

---

Functions Index:
----------------

[](#functions-index)

A

- [afterFirst](#afterfirst)
- [afterLast](#afterlast)
- [append](#append)
- [appendUniqueIdentifier](#appenduniqueidentifier)
- [at](#at)

B

- [beforeFirst](#beforefirst)
- [beforeLast](#beforelast)
- [between](#between)

C

- [camelize](#camelize)
- [chars](#chars)
- [chop](#chop)
- [collapseWhitespace](#collapsewhitespace)
- [contains](#contains)
- [containsAll](#containsall)
- [containsAny](#containsany)
- [countSubstr](#countsubstr)

D

- [dasherize](#dasherize)
- [delimit](#delimit)

E

- [endsWith](#endswith)
- [endsWithAny](#endswithany)
- [ensureLeft](#ensureleft)
- [ensureRight](#ensureright)

F

- [first](#first)

G

- [getString](#getstring)

H

- [hasLowerCase](#haslowercase)
- [hasPrefix](#hasprefix)
- [hasSuffix](#hassuffix)
- [hasUpperCase](#hasuppercase)
- [htmlDecode](#htmldecode)
- [htmlEncode](#htmlencode)
- [humanize](#humanize)

I

- [indexOf](#indexof)
- [indexOfLast](#indexoflast)
- [insert](#insert)
- [isAlpha](#isalpha)
- [isAlphanumeric](#isalphanumeric)
- [isBase64](#isbase64)
- [isBlank](#isblank)
- [isEmail](#isemail)
- [isHexadecimal](#ishexadecimal)
- [isIpV4](#isipv4)
- [isIpV6](#isipv6)
- [isJson](#isjson)
- [isLowerCase](#islowercase)
- [isSerialized](#isserialized)
- [isUUIDv4](#isuuidv4)
- [isUpperCase](#isuppercase)

J

- [join](#join)

L

- [last](#last)
- [length](#length)
- [lines](#lines)
- [longestCommonPrefix](#longestcommonprefix)
- [longestCommonSubstring](#longestcommonsubstring)
- [longestCommonSuffix](#longestcommonsuffix)
- [lowerCaseFirst](#lowercasefirst)

M

- [make](#make)
- [matchesPattern](#matchespattern)
- [move](#move)

O

- [overwrite](#overwrite)

P

- [padBoth](#padboth)
- [padLeft](#padleft)
- [padRight](#padright)
- [pop](#pop)
- [popReversed](#popreversed)
- [prepend](#prepend)

Q

- [quote](#quote)

R

- [random](#random)
- [regexReplace](#regexreplace)
- [removeLeft](#removeleft)
- [removeRight](#removeright)
- [repeat](#repeat)
- [replace](#replace)
- [replaceWithLimit](#replacewithlimit)
- [reverse](#reverse)

S

- [safeTruncate](#safetruncate)
- [shift](#shift)
- [shiftReversed](#shiftreversed)
- [shuffle](#shuffle)
- [slice](#slice)
- [slugify](#slugify)
- [snakeize](#snakeize)
- [split](#split)
- [startsWith](#startswith)
- [startsWithAny](#startswithany)
- [stripWhitespace](#stripwhitespace)
- [substr](#substr)
- [surround](#surround)
- [swapCase](#swapcase)

T

- [tidy](#tidy)
- [titleize](#titleize)
- [toAscii](#toascii)
- [toBoolean](#toboolean)
- [toLowerCase](#tolowercase)
- [toSpaces](#tospaces)
- [toTabs](#totabs)
- [toTitleCase](#totitlecase)
- [toUpperCase](#touppercase)
- [trim](#trim)
- [trimLeft](#trimleft)
- [trimRight](#trimright)
- [truncate](#truncate)

U

- [underscored](#underscored)
- [unquote](#unquote)
- [upperCamelize](#uppercamelize)
- [upperCaseFirst](#uppercasefirst)

W

- [words](#words)

Functions List:
---------------

[](#functions-list)

afterFirst
----------

[](#afterfirst)

Inserts given $substr $times into the original string after the first occurrence of $needle.

```
$str = new Str('foo bar baz');
echo (string)$str->afterFirst('a', 'duh', 2);
// foo baduhduhr baz
```

**Parameters:**

- string $needle
- string $substr
- int $times

**Return:**

- \\Str

---

afterLast
---------

[](#afterlast)

Inserts given $substr $times into the original string after the last occurrence of $needle.

```
$str = new Str('foo bar baz');
echo (string)$str->afterLast('a', 'duh', 2);
// foo bar baduhduhz
```

**Parameters:**

- string $needle
- string $substr
- int $times

**Return:**

- \\Str

---

append
------

[](#append)

Append $sub to the string.

```
$str = new Str('/Acme');
echo (string)$str->append('/');
// /Acme/
```

**Parameters:**

- string $sub

**Return:**

- \\Str

---

appendUniqueIdentifier
----------------------

[](#appenduniqueidentifier)

Appends a random string consisting of $possibleChars, if specified, of given $size or random length between $size and $sizeMax to the original string.

```
$str = new Str('foo');
echo $str->appendUniqueIdentifier(3, -1, 'foba_rz');
// foozro
```

**Parameters:**

- int $size
- int $sizeMax
- string $possibleChars

**Return:**

- \\Str

---

at
--

[](#at)

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

```
$str = new Str('/Acme/');
echo (string)$str->at(2);
// c
```

**Parameters:**

- int $pos

**Return:**

- \\Str

---

beforeFirst
-----------

[](#beforefirst)

Inserts given $substr $times into the original string before the first occurrence of $needle.

```
$str = new Str('foo bar baz');
echo (string)$str->beforeFirst('a', 'duh');
// foo bduhar baz
```

**Parameters:**

- string $needle
- string $substr
- int $times

**Return:**

- \\Str

---

beforeLast
----------

[](#beforelast)

Inserts given $substr $times into the original string before the last occurrence of $needle.

```
$str = new Str('foo bar baz');
echo (string)$str->beforeLast('a', 'duh');
// foo bar bduhaz
```

**Parameters:**

- string $needle
- string $substr
- int $times

**Return:**

- \\Str

---

between
-------

[](#between)

Returns the substring between $start and $end, if found, or an empty string. An optional $offset may be supplied from which to begin the search for the start string.

```
$str = new Str('/Acme/');
echo (string)$str->between('/', '/');
// Acme
```

**Parameters:**

- string $start
- string $end
- int $offset

**Return:**

- \\Str

---

camelize
--------

[](#camelize)

Returns a camelCase version of the string. Trims surrounding spaces, capitalizes letters following digits, spaces, dashes and underscores, and removes spaces, dashes, as well as underscores.

```
$str = new Str('ac me');
echo (string)$str->camelize();
// acMe
```

**Parameters:****nothing**

**Return:**

- \\Str

---

chars
-----

[](#chars)

Returns an array consisting of the characters in the string.

```
$str = new Str('/Acme/');
echo (string)$str->chars();
// ['/', 'A', 'c', 'm', 'e', '/']
```

**Parameters:****nothing**

**Return:**

- array

---

chop
----

[](#chop)

Cuts the original string in pieces of $step size.

```
$str = new Str('foo bar baz');
echo $str->chop(2);
// ['fo', 'o ', 'ba', 'r ', 'ba', 'z']
```

**Parameters:**

- int $step

**Return:**

- array

---

collapseWhitespace
------------------

[](#collapsewhitespace)

Trims the string and replaces consecutive whitespace characters with a single space. This includes tabs and newline characters, as well as multi-byte whitespace such as the thin space and ideographic space.

```
$str = new Str('foo bar baz');
echo (string)$str->collapseWhitespace();
// foo bar baz
```

**Parameters:****nothing**

**Return:**

- \\Str

---

contains
--------

[](#contains)

Check if the string contains $needle substring.

```
$str = new Str('/Acme/');
echo $str->contains('/');
// true
$str = new Str('/Acme/');
echo $str->contains('a', false);
// true
```

**Parameters:**

- string $needle
- bool $caseSensitive

**Return:**

- bool

---

containsAll
-----------

[](#containsall)

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.

```
$str = new Str('/Accmme/');
echo $str->containsAll(['m', 'c', '/']);
// true
```

**Parameters:**

- array $needles
- bool $caseSensitive

**Return:**

- bool

---

containsAny
-----------

[](#containsany)

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.

```
$str = new Str('/Accmme/');
echo $str->containsAny(['foo', 'c', 'bar']);
// true
```

**Parameters:**

- array $needles
- bool $caseSensitive

**Return:**

- bool

---

countSubstr
-----------

[](#countsubstr)

Returns the number of occurrences of $needle in the given string. By default the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.

```
$str = new Str('/Accmme/');
echo $str->countSubstr('m');
// 2
```

**Parameters:**

- string $needle
- bool $caseSensitive

**Return:**

- int

---

dasherize
---------

[](#dasherize)

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.

```
$str = new Str('Ac me');
echo (string)$str->dasherize();
// ac-me
```

**Parameters:****nothing**

**Return:**

- \\Str

---

delimit
-------

[](#delimit)

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.

```
$str = new Str('Ac me');
echo (string)$str->delimit('#');
// ac#me
```

**Parameters:**

- $delimiter

**Return:**

- \\Str

---

endsWith
--------

[](#endswith)

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.

```
$str = new Str('/Accmme/');
echo $str->endsWith('e/');
// true
```

**Parameters:**

- string $substring
- bool $caseSensitive

**Return:**

- bool

---

endsWithAny
-----------

[](#endswithany)

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.

```
$str = new Str('/Accmme/');
echo $str->endsWithAny(['foo', 'e/', 'bar']);
// true
```

**Parameters:**

- array $substrings
- bool $caseSensitive

**Return:**

- bool

---

ensureLeft
----------

[](#ensureleft)

Check whether $prefix exists in the string, and prepend $prefix to the string if it doesn't.

```
$str = new Str('Acme/');
echo (string)$str->ensureLeft('/');
// /Acme/
$str = new Str('/Acme/');
echo (string)$str->ensureLeft('/');
// /Acme/
```

**Parameters:**

- string $check

**Return:**

- \\Str

---

ensureRight
-----------

[](#ensureright)

Check whether $suffix exists in the string, and append $suffix to the string if it doesn't.

```
$str = new Str('/Acme');
echo (string)$str->ensureRight('/'); // /Acme/
$str = new Str('/Acme/');
echo (string)$str->ensureRight('/'); // /Acme/
```

**Parameters:**

- string $check

**Return:**

- \\Str

---

first
-----

[](#first)

Returns the first $length characters of the string.

```
$str = new Str('/Acme/');
echo (string)$str->first(2);
// /A
```

**Parameters:**

- int $length

**Return:**

- \\Str

---

getString
---------

[](#getstring)

**Parameters:****nothing**

**Return:**

- string

---

hasLowerCase
------------

[](#haslowercase)

Returns true if the string contains a lower case char, false otherwise.

```
$str = new Str('Acme');
echo $str->hasLowerCase();
// true
```

**Parameters:****nothing**

**Return:**

- bool

---

hasPrefix
---------

[](#hasprefix)

Check if the string has $prefix at the start.

```
$str = new Str('/Acme/');
echo $str->hasPrefix('/');
// true
```

**Parameters:**

- string $prefix

**Return:**

- bool

---

hasSuffix
---------

[](#hassuffix)

Check if the string has $suffix at the end.

```
$str = new Str('/Acme/');
echo $str->hasSuffix('/');
// true
```

**Parameters:**

- string $suffix

**Return:**

- bool

---

hasUpperCase
------------

[](#hasuppercase)

Returns true if the string contains an upper case char, false otherwise.

```
$str = new Str('Acme');
echo $str->hasUpperCase();
// true
```

**Parameters:****nothing**

**Return:**

- bool

---

htmlDecode
----------

[](#htmldecode)

Convert all HTML entities to their applicable characters. An alias of html\_entity\_decode. For a list of flags, refer to [PHP documentation](http://php.net/manual/en/function.html-entity-decode.php).

```
$str = new Str('&lt;Acme&gt;');
echo (string)$str->htmlDecode();
//
```

**Parameters:**

- int $flags

**Return:**

- \\Str

---

htmlEncode
----------

[](#htmlencode)

Convert all applicable characters to HTML entities. An alias of htmlentities. Refer to [PHP documentation](http://php.net/manual/en/function.htmlentities.php)for a list of flags.

```
$str = new Str('');
echo (string)$str->htmlEncode();
// &lt;Acme&gt;
```

**Parameters:**

- int $flags

**Return:**

- \\Str

---

humanize
--------

[](#humanize)

Capitalizes the first word of the string, replaces underscores with spaces.

```
$str = new Str('foo_id');
echo (string)$str->humanize();
// Foo
```

**Parameters:****nothing**

**Return:**

- \\Str

---

indexOf
-------

[](#indexof)

Returns the index of the first occurrence of $needle in the string, and -1 if not found. Accepts an optional $offset from which to begin the search.

```
$str = new Str('/Accmme/');
echo $str->indexOf('m');
// 4
```

**Parameters:**

- string $needle
- int $offset

**Return:**

- int

---

indexOfLast
-----------

[](#indexoflast)

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.

```
$str = new Str('/Accmme/');
echo $str->indexOfLast('m');
// 5
```

**Parameters:**

- string $needle
- int $offset

**Return:**

- int

---

insert
------

[](#insert)

Inserts $substring into the string at the $index provided.

```
$str = new Str('/Ace/');
echo (string)$str->insert('m', 3);
// /Acme/
```

**Parameters:**

- string $substring
- int $index

**Return:**

- \\Str

---

isAlpha
-------

[](#isalpha)

Returns true if the string contains only alphabetic chars, false otherwise.

```
$str = new Str('Acme');
echo $str->isAlpha();
// true
```

**Parameters:****nothing**

**Return:**

- bool

---

isAlphanumeric
--------------

[](#isalphanumeric)

Returns true if the string contains only alphabetic and numeric chars, false otherwise.

```
$str = new Str('Acme1');
echo $str->isAlphanumeric();
// true
```

**Parameters:****nothing**

**Return:**

- bool

---

isBase64
--------

[](#isbase64)

Check if this string is valid base64 encoded data. Function do encode(decode(s)) === s, so this is not so fast.

**Parameters:****nothing**

**Return:**

- bool

---

isBlank
-------

[](#isblank)

Returns true if the string contains only whitespace chars, false otherwise.

```
$str = new Str('Acme');
echo $str->isBlank();
// false
```

**Parameters:****nothing**

**Return:**

- bool

---

isEmail
-------

[](#isemail)

Splits the original string in pieces by '@' delimiter and returns true in case the resulting array consists of 2 parts.

```
$str = new Str('test@test@example.com');
echo $str->isEmail();
// false
```

**Parameters:****nothing**

**Return:**

- bool

---

isHexadecimal
-------------

[](#ishexadecimal)

Returns true if the string contains only hexadecimal chars, false otherwise.

```
$str = new Str('Acme');
echo $str->isHexadecimal();
// false
```

**Parameters:****nothing**

**Return:**

- bool

---

isIpV4
------

[](#isipv4)

Return true if this is valid ipv4 address

```
$str = new Str('1.0.1.0');
echo $str->isIpV4();
// true
```

**Parameters:****nothing**

**Return:**

- bool

---

isIpV6
------

[](#isipv6)

Return true if this is valid ipv6 address

```
$str = new Str('2001:cdba::3257:9652');
echo $str->isIpV6();
// true
```

**Parameters:****nothing**

**Return:**

- bool

---

isJson
------

[](#isjson)

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.

```
$str = new Str('Acme');
echo $str->isJson();
// false
```

**Parameters:****nothing**

**Return:**

- bool

---

isLowerCase
-----------

[](#islowercase)

Returns true if the string contains only lower case chars, false otherwise.

```
$str = new Str('Acme');
echo $str->isLowerCase();
// false
```

**Parameters:****nothing**

**Return:**

- bool

---

isSerialized
------------

[](#isserialized)

Returns true if the string is serialized, false otherwise.

```
$str = new Str('Acme');
echo $str->isSerialized();
// false
```

**Parameters:****nothing**

**Return:**

- bool

---

isUUIDv4
--------

[](#isuuidv4)

It doesn't matter whether the given UUID has dashes.

```
$str = new Str('76d7cac8-1bd7-11e8-accf-0ed5f89f718b');
echo $str->isUUIDv4();
// false
$str = new Str('ae815123-537f-4eb3-a9b8-35881c29e1ac');
echo $str->isUUIDv4();
// true
```

**Parameters:****nothing**

**Return:**

- bool

---

isUpperCase
-----------

[](#isuppercase)

Returns true if the string contains only upper case chars, false otherwise.

```
$str = new Str('Acme');
echo $str->isUpperCase();
// false
```

**Parameters:****nothing**

**Return:**

- bool

---

join
----

[](#join)

Joins the original string with an array of other strings with the given $separator.

```
$str = new Str('foo');
echo $str->join('*', ['bar', 'baz']);
// foo*bar*baz
```

**Parameters:**

- string $separator
- array $otherStrings

**Return:**

- \\Str

---

last
----

[](#last)

Returns the first $length characters of the string.

```
$str = new Str('/Acme/');
echo (string)$str->last(2);
// e/
```

**Parameters:**

- int $length

**Return:**

- \\Str

---

length
------

[](#length)

Returns the length of the string.

```
$str = new Str('/Acme/');
echo $str->length();
// 6
```

**Parameters:****nothing**

**Return:**

- int

---

lines
-----

[](#lines)

Splits on newlines and carriage returns, returning an array of strings corresponding to the lines in the string.

```
$str = new Str("Acme\r\nAcme");
echo $str->lines();
// ['Acme', 'Acme']
```

**Parameters:****nothing**

**Return:**

- array

---

longestCommonPrefix
-------------------

[](#longestcommonprefix)

Returns the longest common prefix between the string and $otherStr.

```
$str = new Str('Acme');
echo (string)$str->longestCommonPrefix('Accurate');
// Ac
```

**Parameters:**

- string $otherStr

**Return:**

- \\Str

---

longestCommonSubstring
----------------------

[](#longestcommonsubstring)

Returns the longest common substring between the string and $otherStr. In the case of ties, it returns that which occurs first.

```
$str = new Str('Acme');
echo (string)$str->longestCommonSubstring('meh');
// me
```

**Parameters:**

- string $otherStr

**Return:**

- \\Str

---

longestCommonSuffix
-------------------

[](#longestcommonsuffix)

Returns the longest common suffix between the string and $otherStr.

```
$str = new Str('Acme');
echo (string)$str->longestCommonSuffix('Do believe me');
// me
```

**Parameters:**

- string $otherStr

**Return:**

- \\Str

---

lowerCaseFirst
--------------

[](#lowercasefirst)

Converts the first character of the string to lower case.

```
$str = new Str('Acme Foo');
echo (string)$str->lowerCaseFirst();
// acme Foo
```

**Parameters:****nothing**

**Return:**

- \\Str

---

make
----

[](#make)

Create a new Str object using static method for it.

```
$str = Str::make('Acme');
echo (string)$str; // Acme
```

**Parameters:**

- string $str

**Return:**

- \\Str

---

matchesPattern
--------------

[](#matchespattern)

Returns true if the string match regexp pattern

```
$s = new Str('foo baR');
echo $str->matchesPattern('.*aR');
// true
```

**Parameters:**

- string $pattern

**Return:**

- bool

---

move
----

[](#move)

Move substring of desired $length to $destination index of the original string. In case $destination is less than $length returns the string untouched.

```
$str = new Str('/Acme/');
echo (string)$str->move(0, 2, 4);
// cm/Ae/
```

**Parameters:**

- int $start
- int $length
- int $destination

**Return:**

- \\Str

---

overwrite
---------

[](#overwrite)

Replaces substring in the original string of $length with given $substr.

```
$str = new Str('/Acme/');
echo (string)$str->overwrite(0, 2, 'BAR');
// BARcme/
```

**Parameters:**

- int $start
- int $length
- string $substr

**Return:**

- \\Str

---

padBoth
-------

[](#padboth)

Returns a new string of a given length such that both sides of the string are padded.

```
$str = new Str('Acme');
echo (string)$str->padBoth(6, '/');
// /Acme/
```

**Parameters:**

- int $length
- string $padStr

**Return:**

- \\Str

---

padLeft
-------

[](#padleft)

Returns a new string of a given length such that the beginning of the string is padded.

```
$str = new Str('Acme/');
echo (string)$str->padLeft(6, '/');
// /Acme/
```

**Parameters:**

- int $length
- string $padStr

**Return:**

- \\Str

---

padRight
--------

[](#padright)

Returns a new string of a given length such that the end of the string is padded.

```
$str = new Str('/Acme');
echo (string)$str->padRight(6, '/');
// /Acme/
```

**Parameters:**

- int $length
- string $padStr

**Return:**

- \\Str

---

pop
---

[](#pop)

Returns the substring of the string from the last occurrence of $delimiter to the end.

```
$str = new Str('Acme/foo');
echo $str->pop('/');
// foo
```

**Parameters:**

- string $delimiter

**Return:**

- \\Str

---

popReversed
-----------

[](#popreversed)

Returns the substring of the original string from the beginning to the last occurrence of $delimiter.

```
$str = new Str('Acme/foo/bar');
echo $str->popReversed('/');
// Acme/foo
```

**Parameters:**

- string $delimiter

**Return:**

- \\Str

---

prepend
-------

[](#prepend)

Prepend $sub to the string.

```
$str = new Str('Acme/');
echo (string)$str->prepend('/');
// /Acme/
```

**Parameters:**

- string $sub

**Return:**

- \\Str

---

quote
-----

[](#quote)

Wraps each word in the string with specified $quote.

```
$str = new Str('foo bar baz');
echo $str->quote('*');
// *foo* *bar* *baz*
```

**Parameters:**

- string $quote

**Return:**

- \\Str

---

random
------

[](#random)

Generates a random string consisting of $possibleChars, if specified, of given $size or random length between $size and $sizeMax. If $possibleChars is not specified, the generated string will consist of ASCII alphanumeric chars.

```
$str = new Str('foo bar');
echo $str->random(3, -1, 'fobarz');
// zfa
$str = new Str('');
echo $str->random(3);
// 1ho
```

**Parameters:**

- int $size
- int $sizeMax
- string $possibleChars

**Return:**

- \\Str

---

regexReplace
------------

[](#regexreplace)

Replaces all occurrences of $pattern in the string by $replacement. An alias for mb\_ereg\_replace(). Note that the 'i' option with multi-byte patterns in mb\_ereg\_replace() requires PHP 5.6+ for correct results. This is due to a lack of support in the bundled version of Oniguruma in PHP &lt; 5.6, and current versions of HHVM (3.8 and below).

```
$str = new Str('Acme Foo');
echo (string)$str->regexReplace('A', 'a');
// acme Foo
```

**Parameters:**

- string $pattern
- string $replacement
- string $options

**Return:**

- \\Str

---

removeLeft
----------

[](#removeleft)

Returns the string with the prefix $substring removed, if present.

```
$str = new Str('/Acme/');
echo (string)$str->removeLeft('/');
// Acme/
```

**Parameters:**

- string $substring

**Return:**

- \\Str

---

removeRight
-----------

[](#removeright)

Returns the string with the suffix $substring removed, if present.

```
$str = new Str('/Acme/');
echo (string)$str->removeRight('/');
// /Acme
```

**Parameters:**

- string $substring

**Return:**

- \\Str

---

repeat
------

[](#repeat)

Returns a repeated string given a $multiplier. An alias for str\_repeat.

```
$str = new Str('Acme/');
echo (string)$str->repeat(2);
// Acme/Acme/
```

**Parameters:**

- int $multiplier

**Return:**

- \\Str

---

replace
-------

[](#replace)

Replaces all occurrences of $old in the string by $new.

```
$str = new Str('/Acme/');
echo (string)$str->replace('/', '#');
// #Acme#
```

**Parameters:**

- string $old
- string $new

**Return:**

- \\Str

---

replaceWithLimit
----------------

[](#replacewithlimit)

Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n &lt; 0, there is no limit on the number of replacements.

```
$str = new Str('/Acme/');
echo (string)$str->replaceWithLimit('/', '#', 1);
// #Acme/
```

**Parameters:**

- string $old
- string $new
- int $limit

**Return:**

- \\Str

---

reverse
-------

[](#reverse)

Returns a reversed string. A multi-byte version of strrev().

```
$str = new Str('/Acme/');
echo (string)$str->reverse();
// /emcA/
```

**Parameters:****nothing**

**Return:**

- \\Str

---

safeTruncate
------------

[](#safetruncate)

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.

```
$str = new Str('What are your plans today?');
echo (string)$str->safeTruncate(22, '...');
// What are your plans...
```

**Parameters:**

- int $length
- string $substring

**Return:**

- \\Str

---

shift
-----

[](#shift)

Returns the substring of the original string from beginning to the first occurrence of $delimiter.

```
$str = new Str('Acme/foo');
echo $str->shift('/');
// Acme
```

**Parameters:**

- string $delimiter

**Return:**

- \\Str

---

shiftReversed
-------------

[](#shiftreversed)

Returns the substring of the original string from the first occurrence of $delimiter to the end.

```
$str = new Str('Acme/foo/bar');
echo $str->shiftReversed('/');
// foo/bar
```

**Parameters:**

- string $delimiter

**Return:**

- \\Str

---

shuffle
-------

[](#shuffle)

A multi-byte str\_shuffle() function. It returns a string with its characters in random order.

```
$str = new Str('/Acme/');
echo (string)$str->shuffle();
// mAe//c
```

**Parameters:****nothing**

**Return:**

- \\Str

---

slice
-----

[](#slice)

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.

```
$str = new Str('Acme');
echo (string)$str->slice(2);
// me
```

**Parameters:**

- int $start
- int|null $end

**Return:**

- \\Str

---

slugify
-------

[](#slugify)

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 $replacement. The $replacement 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.

```
$str = new Str('Acme foo bar!');
echo (string)$str->slugify();
// acme-foo-bar
```

**Parameters:**

- string $replacement
- string $language

**Return:**

- \\Str

---

snakeize
--------

[](#snakeize)

Returns a snake\_case version of the string.

```
$str = new Str('Foo Bar');
echo (string)$str->snakeize();
// foo_bar
```

**Parameters:****nothing**

**Return:**

- \\Str

---

split
-----

[](#split)

Splits the string with the provided $pattern, returning an array of strings. An optional integer $limit will truncate the results.

```
$str = new Str('Acme#Acme');
echo $str->split('#', 1);
// ['Acme']
```

**Parameters:**

- string $pattern
- int $limit

**Return:**

- array

---

startsWith
----------

[](#startswith)

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.

```
$str = new Str('/Accmme/');
echo $str->startsWith('/A');
// true
```

**Parameters:**

- string $substring
- bool $caseSensitive

**Return:**

- bool

---

startsWithAny
-------------

[](#startswithany)

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.

```
$str = new Str('/Accmme/');
echo $str->startsWithAny(['foo', '/A', 'bar']);
// true
```

**Parameters:**

- array $substrings
- bool $caseSensitive

**Return:**

- bool

---

stripWhitespace
---------------

[](#stripwhitespace)

Strip all whitespace characters. This includes tabs and newline characters, as well as multi-byte whitespace such as the thin space and ideographic space.

```
$str = new Str('Acme foo');
echo (string)$str->stripWhitespace();
// Acmefoo
```

**Parameters:****nothing**

**Return:**

- \\Str

---

substr
------

[](#substr)

Returns the substring beginning at $start with the specified $length. It differs from the mb\_substr() function in that providing a $length of 0 will return the rest of the string, rather than an empty string.

```
$str = new Str('/Acme/');
echo (string)$str->substr(1, 4);
// Acme
```

**Parameters:**

- int $start
- int $length

**Return:**

- \\Str

---

surround
--------

[](#surround)

Surrounds the string with the given $substring.

```
$str = new Str('Acme');
echo (string)$str->surround('/');
// /Acme/
```

**Parameters:**

- string $substring

**Return:**

- \\Str

---

swapCase
--------

[](#swapcase)

Returns a case swapped version of the string.

```
$str = new Str('foObARbAz');
echo (string)$str->swapCase();
// FOoBarBaZ
```

**Parameters:****nothing**

**Return:**

- \\Str

---

tidy
----

[](#tidy)

Returns a string with smart quotes, ellipsis characters, and dashes from Windows-1252 (commonly used in Word documents) replaced by their ASCII equivalents.

```
$str = new Str('“I see…”');
echo (string)$str->tidy();
// "I see..."
```

**Parameters:****nothing**

**Return:**

- \\Str

---

titleize
--------

[](#titleize)

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.

```
$str = new Str('i like to watch DVDs at home');
echo (string)$str->titleize(['at', 'to', 'the']);
// I Like to Watch Dvds at Home
```

**Parameters:**

- array $ignore

**Return:**

- \\Str

---

toAscii
-------

[](#toascii)

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.

```
$str = new Str('Äcmế');
echo (string)$str->toAscii();
// Acme
```

**Parameters:**

- string $language
- bool $removeUnsupported

**Return:**

- \\Str

---

toBoolean
---------

[](#toboolean)

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.

```
$str = new Str('yes');
echo $str->toBoolean();
// true
```

**Parameters:****nothing**

**Return:**

- bool

---

toLowerCase
-----------

[](#tolowercase)

Make the string lowercase.

```
$str = new Str('/Acme/');
echo (string)$str->toLowerCase();
// /acme/
```

**Parameters:****nothing**

**Return:**

- \\Str

---

toSpaces
--------

[](#tospaces)

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.

```
$str = new Str('foo    bar');
echo (string)$str->toSpaces(0);
// foobar
```

**Parameters:**

- int $tabLength

**Return:**

- \\Str

---

toTabs
------

[](#totabs)

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.

```
$str = new Str('foo bar');
echo (string)$str->toTabs();
// foo    bar
```

**Parameters:**

- int $tabLength

**Return:**

- \\Str

---

toTitleCase
-----------

[](#totitlecase)

Converts the first character of each word in the string to uppercase.

```
$str = new Str('foo bar baz');
echo (string)$str->toTitleCase();
// Foo Bar Baz
```

**Parameters:****nothing**

**Return:**

- \\Str

---

toUpperCase
-----------

[](#touppercase)

Make the string uppercase.

```
$str = new Str('/Acme/');
echo (string)$str->toUpperCase();
// /ACME/
```

**Parameters:****nothing**

**Return:**

- \\Str

---

trim
----

[](#trim)

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.

```
$str = new Str('/Acme/');
echo (string)$str->trim('/');
// Acme
```

**Parameters:**

- string $chars

**Return:**

- \\Str

---

trimLeft
--------

[](#trimleft)

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.

```
$str = new Str('/Acme/');
echo (string)$str->trimLeft('/');
// Acme/
```

**Parameters:**

- string $chars

**Return:**

- \\Str

---

trimRight
---------

[](#trimright)

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.

```
$str = new Str('/Acme/');
echo (string)$str->trimRight('/');
// /Acme
```

**Parameters:**

- string $chars

**Return:**

- \\Str

---

truncate
--------

[](#truncate)

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.

```
$str = new Str('What are your plans today?');
echo (string)$str->truncate(19, '...');
// What are your pl...
```

**Parameters:**

- int $length
- string $substring

**Return:**

- \\Str

---

underscored
-----------

[](#underscored)

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.

```
$str = new Str('foo Bar baz');
echo (string)$str->underscored();
// foo_bar_baz
```

**Parameters:****nothing**

**Return:**

- \\Str

---

unquote
-------

[](#unquote)

Unwraps each word in the original string, deleting the specified $quote.

```
$str = new Str('*foo* bar* ***baz*');
echo $str->unquote('*');
// foo bar baz
```

**Parameters:**

- string $quote

**Return:**

- \\Str

---

upperCamelize
-------------

[](#uppercamelize)

Returns an UpperCamelCase version of the string. It trims surrounding spaces, capitalizes letters following digits, spaces, dashes and underscores, and removes spaces, dashes, underscores.

```
$str = new Str('foo bar baz');
echo (string)$str->upperCamelize();
// FooBarBaz
```

**Parameters:****nothing**

**Return:**

- \\Str

---

upperCaseFirst
--------------

[](#uppercasefirst)

Converts the first character of the string to upper case.

```
$str = new Str('acme foo');
echo (string)$str->upperCaseFirst();
// Acme foo
```

**Parameters:****nothing**

**Return:**

- \\Str

---

words
-----

[](#words)

Splits on whitespace, returning an array of strings corresponding to the words in the string.

```
$str = new Str('foo bar baz');
echo $str->words();
// ['foo', 'bar', 'baz']
```

**Parameters:****nothing**

**Return:**

- array

---

---

Benchmark
---------

[](#benchmark)

lib code tests (versus):

```
make lib-code-tests
```

how to get total RANK:

```
make rank
```

generate md:

```
make md
```

run tests:

```
make test
```

Test subjects:

- FS ([str/str](https://github.com/fe3dback/str))
- Stringy ([danielstjules/Stringy](https://github.com/danielstjules/Stringy))

---

RANK (sum time of all benchmarks): **smaller - is better!**

TargetTotal TimeDiffStr5.505 s.1xStringy10.840 s.2.0x---

subjectmodemem\_peakdiffbench\_common\_Str811.098μs1,929,728b1.00xbench\_common\_Stringy5,310.290μs1,879,272b6.55x##### [see all other benchmark results](https://github.com/fe3dback/str/blob/master/docs/benchmark.md)

[](#see-all-other-benchmark-results)

Development
-----------

[](#development)

Please use php cs fixer before commit:

you can add watcher in any IDE for automatic fix code style on save.

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity46

Moderate usage in the ecosystem

Community24

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 52.9% of commits — single point of failure

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 ~140 days

Recently: every ~258 days

Total

9

Last Release

1884d ago

Major Versions

v0.3.0 → v1.0.02018-03-29

PHP version history (3 changes)v0.1.0PHP &gt;=7.0.0

v1.1.0PHP &gt;=7.1.0

1.1.3PHP &gt;=7.2.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/e6fad0f59a23c50af19966a2cd9351a5b70be5511831b7ce7f7e6dac52942e5b?d=identicon)[fe3dback](/maintainers/fe3dback)

---

Top Contributors

[![irhen](https://avatars.githubusercontent.com/u/27947960?v=4)](https://github.com/irhen "irhen (63 commits)")[![fe3dback](https://avatars.githubusercontent.com/u/2073883?v=4)](https://github.com/fe3dback "fe3dback (51 commits)")[![MarkusFoitzikC24](https://avatars.githubusercontent.com/u/141918422?v=4)](https://github.com/MarkusFoitzikC24 "MarkusFoitzikC24 (4 commits)")[![shadowhand](https://avatars.githubusercontent.com/u/38203?v=4)](https://github.com/shadowhand "shadowhand (1 commits)")

---

Tags

librarymultibytephpphp-librarystrstringstring-manipulationstringyutf-8

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/str-str/health.svg)

```
[![Health](https://phpackages.com/badges/str-str/health.svg)](https://phpackages.com/packages/str-str)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
