PHPackages                             spatie/string - 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. spatie/string

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

spatie/string
=============

String handling evolved

3.0.1(1mo ago)5604.6M↓25.9%2620MITPHPPHP ^8.0CI passing

Since Jun 5Pushed 1mo ago13 watchersCompare

[ Source](https://github.com/spatie/string)[ Packagist](https://packagist.org/packages/spatie/string)[ Docs](https://github.com/spatie/string)[ Fund](https://spatie.be/open-source/support-us)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/spatie-string/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (10)Dependencies (5)Versions (25)Used By (20)

String handling evolved
=======================

[](#string-handling-evolved)

[![Latest Version on Packagist](https://camo.githubusercontent.com/fb1266006d8bc9dd58494fcc4a6351d9a95c23a053bc5d0ef70a2313078c4114/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f737472696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/string)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/9d05ab1789aa70d32caa5f88301599e534c6d8740a9ec56dccc117003416bee7/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f7370617469652f737472696e672f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/spatie/string)[![Quality Score](https://camo.githubusercontent.com/2a385c55bef7dcd1ede2b95ff15a7d28cfd7bfa7e235f9fbcc885846f97021a4/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7370617469652f737472696e672e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/spatie/string)[![Total Downloads](https://camo.githubusercontent.com/8afe6f35416baad429f1d44053c9d988bb960bcfc80e5c8dc19b681aa25cfc5d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f737472696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/string)

This package provides a handy way to work with strings in php.

Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/8c6ee30cb02913386951d979c2573bdc47849d9b7ef3df66fd981c262f513cc5/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f737472696e672e6a70673f743d31)](https://spatie.be/github-ad-click/string)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Install
-------

[](#install)

You can install this package via composer:

```
composer require spatie/string
```

Usage
-----

[](#usage)

First you must wrap a native string in a String-object. This can be done with the `string`-function.

```
string('myFirstString');
```

From then on you can chain methods like there's no tomorrow:

```
echo string('StartMiddleEnd')->between('Start', 'End')->toUpper(); // outputs "MIDDLE"
```

Of course you can keep concatenate the output with the `.`-operator we all know and love.

```
echo 'stuck in the ' . string('StartMiddleEnd')->between('Start', 'End')->toLower() . ' with you';
```

You can also use offsets to manipulate a string.

```
echo string('hello')[1]->toUpper(); //outputs "E"

$string = string('gray');
$string[2] = 'e';
echo $string->toUpper(); //outputs "GREY"
```

Provided methods
----------------

[](#provided-methods)

### between

[](#between)

```
/**
 * Get the string between the given start and end.
 *
 * @param $start
 * @param $end
 * @return \Spatie\String\String
 */
public function between($start, $end)
```

Example:

```
string('StartMiddleEnd')->between('Start', 'End')->toUpper(); // MIDDLE
```

### toUpper

[](#toupper)

```
/**
 * Convert the string to uppercase.
 *
 * @return \Spatie\String\String
 */
public function toUpper()
```

Example:

```
string('string')->toUpper(); // STRING
```

### toLower

[](#tolower)

```
/**
 * Convert the string to lowercase.
 *
 * @return \Spatie\String\String
 */
public function toLower()
```

Example:

```
string('STRING')->toLower(); // string
```

### tease

[](#tease)

```
/**
 * Shortens a string in a pretty way. It will clean it by trimming
 * it, remove all double spaces and html. If the string is then still
 * longer than the specified $length it will be shortened. The end
 * of the string is always a full word concatinated with the
 * specified moreTextIndicator.
 *
 * @param int $length
 * @param string $moreTextIndicator
 * @return \Spatie\String\String
 */
public function tease($length = 200, $moreTextIndicator = '...')
```

Example:

```
$longText = 'Now that there is the Tec-9, a crappy spray gun from South Miami. This gun is advertised as the most popular gun in American crime. Do you believe that shit? It actually says that in the little book that comes with it: the most popular gun in American crime.'
string($longText)->tease(10); // Now that...
```

### replaceFirst

[](#replacefirst)

```
/**
 * Replace the first occurrence of a string.
 *
 * @param $search
 * @param $replace
 * @return \Spatie\String\String
 */
public function replaceFirst($search, $replace)
```

Example:

```
$sentence = 'A good thing is not a good thing.';
string($sentence)->replaceFirst('good', 'bad'); // A bad thing is not a good thing.
```

### replaceLast

[](#replacelast)

```
/**
 * Replace the last occurrence of a string.
 *
 * @param $search
 * @param $replace
 * @return \Spatie\String\String
 */
public function replaceLast($search, $replace)
```

Example:

```
$sentence = 'A good thing is not a good thing.';
string($sentence)->replaceLast('good', 'bad'); // A good thing is not a bad thing.
```

### prefix

[](#prefix)

```
/**
 * Prefix a string.
 *
 * @param $string
 * @return \Spatie\String\String
 */
public function prefix($string)
```

Example:

```
string('world')->prefix('hello '); //hello world
```

### suffix

[](#suffix)

```
/**
 * Suffix a string.
 *
 * @param $string
 * @return \Spatie\String\String
 */
public function suffix($string)
```

Example:

```
string('hello')->suffix(' world'); // hello world
```

### concat

[](#concat)

This is identical to the `suffix`-function.

### possessive

[](#possessive)

```
/**
 * Get the possessive version of a string.
 *
 * @return \Spatie\String\String
 */
public function possessive()
```

Example:

```
string('Bob')->possessive(); // Bob's
string('Charles')->possessive(); // Charles'
```

### segment

[](#segment)

```
/**
 * Get a segment from a string based on a delimiter.
 * Returns an empty string when the offset doesn't exist.
 * Use a negative index to start counting from the last element.
 *
 * @param string $delimiter
 * @param int $index
 *
 * @return \Spatie\String\String
 */
public function segment($delimiter, $index)
```

Related methods:

```
/**
 * Get the first segment from a string based on a delimiter.
 *
 * @param string $delimiter
 *
 * @return \Spatie\String\String
 */
public function firstSegment($delimiter)

/**
 * Get the last segment from a string based on a delimiter.
 *
 * @param string $delimiter
 *
 * @return \Spatie\String\String
 */
public function lastSegment($delimiter)
```

Example:

```
string('foo/bar/baz')->segment('/', 0); // foo
string('foo/bar/baz')->segment('/', 1); // bar
string('foo/bar/baz')->firstSegment('/'); // foo
string('foo/bar/baz')->lastSegment('/'); // baz
```

pop
---

[](#pop)

```
/**
 * Pop (remove) the last segment of a string based on a delimiter
 *
 * @param string $delimiter
 *
 * @return \Spatie\String\String
 */
public function pop($delimiter)
```

Example:

```
string('foo/bar/baz')->pop('/'); // foo/bar
string('foo/bar/baz')->pop('/')->pop('/'); // foo
```

contains
--------

[](#contains)

```
/**
 * Check whether a string contains a substring
 *
 * @param array|string $needle
 * @param bool $caseSensitive
 * @param bool $absolute
 *
 * @return bool
 */
public function contains($delimiter)
```

Example:

```
string('hello world')->contains('world'); // true
string('hello world')->contains('belgium'); // false
```

Integration with underscore.php
-------------------------------

[](#integration-with-underscorephp)

In addition to the methods described above, you can also use [all string methods](https://github.com/Anahkiasen/underscore-php/blob/master/src/Methods/StringsMethods.php) provided by [Maxime Fabre's underscore package](https://github.com/Anahkiasen/underscore-php).

For example:

```
string('i am a slug')->slugify()` // returns 'i-am-a-slug'
```

Of course, you can chain underscore's methods with our own.

```
string('i am a slug')->slugify()->between('i', 'a-slug`) // returns '-am-'
```

Be aware that some underscore methods do not return a string value. Such methods are not chainable.

```
string('freek@spatie.be')->isEmail() // returns true;
```

Testing
-------

[](#testing)

You can run the tests with:

```
vendor/bin/phpunit
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

About Spatie
------------

[](#about-spatie)

Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource).

Alternatives
------------

[](#alternatives)

This package is primarily built for usage in our own projects. If you need a more full fledged string package take at look at these ones:

- [Anahkiasen/underscore-php](https://github.com/Anahkiasen/underscore-php)
- [danielstjules/Stringy](https://github.com/danielstjules/Stringy)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

70

—

ExcellentBetter than 100% of packages

Maintenance89

Actively maintained with recent releases

Popularity62

Solid adoption and visibility

Community35

Small or concentrated contributor base

Maturity78

Established project with proven stability

 Bus Factor1

Top contributor holds 65.5% 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 ~180 days

Recently: every ~856 days

Total

23

Last Release

53d ago

Major Versions

0.0.1 → 1.0.02015-06-05

1.9.1 → 2.0.02015-07-13

2.2.3 → 3.0.02021-03-30

PHP version history (5 changes)0.0.1PHP &gt;=5.4.0

2.0.0PHP &gt;=5.5.0

2.2.0PHP &gt;=5.6.0

2.2.3PHP ^7.0|^8.0

3.0.0PHP ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (76 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (21 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (8 commits)")[![patinthehat](https://avatars.githubusercontent.com/u/5508707?v=4)](https://github.com/patinthehat "patinthehat (3 commits)")[![carusogabriel](https://avatars.githubusercontent.com/u/16328050?v=4)](https://github.com/carusogabriel "carusogabriel (2 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 commits)")[![willemvb](https://avatars.githubusercontent.com/u/1336390?v=4)](https://github.com/willemvb "willemvb (2 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (1 commits)")[![yogasukma](https://avatars.githubusercontent.com/u/1949957?v=4)](https://github.com/yogasukma "yogasukma (1 commits)")

---

Tags

phpstringspatiestringhandlinghandy

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[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)[spatie/laravel-package-tools

Tools for creating Laravel packages

946138.7M8.7k](/packages/spatie-laravel-package-tools)[spatie/laravel-data

Create unified resources and data transfer objects

1.8k33.0M871](/packages/spatie-laravel-data)[spatie/macroable

A trait to dynamically add methods to a class

72962.7M72](/packages/spatie-macroable)[spatie/regex

A sane interface for php's built in preg\_\* functions

1.1k18.9M68](/packages/spatie-regex)[spatie/enum

PHP Enums

84731.4M74](/packages/spatie-enum)

PHPackages © 2026

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