Top Related Projects
Doctrine Inflector is a small library that can perform string manipulations with regard to uppercase/lowercase and singular/plural forms of words.
Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way
:snowflake: A PHP library for generating universally unique identifiers (UUIDs).
A redacted PHP port of Underscore.js with additional functions and goodies – Available for Composer and Laravel
Quick Overview
Stringy is a PHP string manipulation library that provides a fluent, object-oriented interface for working with strings. It offers a wide range of methods for tasks such as case manipulation, substring extraction, and string transformation, making it easier to work with strings in PHP applications.
Pros
- Fluent, chainable API for easy string manipulation
- Extensive set of methods covering various string operations
- Unicode support for handling multi-byte characters
- Well-documented and actively maintained
Cons
- Adds an additional dependency to projects
- May have a slight performance overhead compared to native PHP string functions
- Learning curve for developers used to traditional PHP string manipulation
- Some operations might be redundant with PHP's built-in functions
Code Examples
Creating a Stringy object and performing operations:
use Stringy\Stringy as S;
$string = S::create('fòôbàř');
echo $string->toAscii(); // foobAR
Chaining multiple operations:
use Stringy\Stringy as S;
$result = S::create(' Hello, World! ')
->trim()
->toLowerCase()
->replace('hello', 'Hi')
->append('!')
->upperCaseFirst();
echo $result; // Hi, world!!
Working with substrings:
use Stringy\Stringy as S;
$string = S::create('Fòôbàř');
echo $string->substr(0, 3); // Fòô
echo $string->safeTruncate(3, '...'); // Fò...
Getting Started
To use Stringy in your PHP project, follow these steps:
-
Install Stringy using Composer:
composer require danielstjules/stringy
-
In your PHP file, use the Stringy namespace and create a Stringy object:
use Stringy\Stringy as S; $string = S::create('Hello, World!');
-
Start manipulating strings using the available methods:
echo $string->toLowerCase()->append('!!'); // hello, world!!!
Competitor Comparisons
Doctrine Inflector is a small library that can perform string manipulations with regard to uppercase/lowercase and singular/plural forms of words.
Pros of Inflector
- More focused on inflection and pluralization rules
- Part of the larger Doctrine project, potentially better integration with other Doctrine components
- Supports multiple languages for inflection rules
Cons of Inflector
- Less comprehensive string manipulation functionality
- Fewer methods for general string operations
- May be overkill if only basic string manipulation is needed
Code Comparison
Stringy:
use Stringy\Stringy as S;
$string = S::create('fòôbàř');
echo $string->toAscii(); // foobAr
echo $string->slugify(); // foobar
Inflector:
use Doctrine\Inflector\InflectorFactory;
$inflector = InflectorFactory::create()->build();
echo $inflector->pluralize('child'); // children
echo $inflector->singularize('teeth'); // tooth
Summary
Stringy is a more comprehensive string manipulation library, offering a wide range of methods for various string operations. Inflector, on the other hand, specializes in inflection and pluralization rules, with support for multiple languages. Choose Stringy for general string manipulation tasks, and Inflector for specific inflection needs or when working within the Doctrine ecosystem.
Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way
Pros of String
- Part of the larger Symfony ecosystem, offering better integration with other Symfony components
- More actively maintained with frequent updates and improvements
- Supports Unicode string manipulations out of the box
Cons of String
- Heavier dependency due to being part of the Symfony framework
- May have a steeper learning curve for developers not familiar with Symfony
Code Comparison
Stringy:
use Stringy\Stringy as S;
$string = S::create('fòôbàř');
echo $string->toAscii(); // foobAr
String:
use Symfony\Component\String\UnicodeString;
$string = new UnicodeString('fòôbàř');
echo $string->ascii(); // foobAr
Both libraries offer similar functionality for string manipulation, but Symfony's String component provides a more modern and Unicode-aware approach. While Stringy uses a static factory method, String uses object instantiation. The method names differ slightly, but the overall usage is comparable.
String is generally recommended for projects already using Symfony or requiring extensive Unicode support. Stringy might be preferred for simpler projects or those seeking a lightweight string manipulation library.
:snowflake: A PHP library for generating universally unique identifiers (UUIDs).
Pros of UUID
- Specialized for generating and working with UUIDs
- Supports multiple UUID versions (1, 3, 4, 5, 6)
- Provides UUID validation and parsing functionality
Cons of UUID
- Limited to UUID-related operations
- Lacks string manipulation features
- Requires additional dependencies for certain UUID versions
Code Comparison
UUID:
use Ramsey\Uuid\Uuid;
$uuid = Uuid::uuid4();
echo $uuid->toString();
Stringy:
use Stringy\Stringy as S;
$string = S::create('fòôbàř');
echo $string->toAscii();
Summary
UUID is a specialized library for generating and manipulating UUIDs, offering support for multiple UUID versions and validation. However, it lacks general string manipulation features. Stringy, on the other hand, is a more versatile string manipulation library but doesn't provide UUID-specific functionality.
UUID is ideal for projects requiring extensive UUID handling, while Stringy is better suited for general string operations. The choice between the two depends on the specific needs of your project.
A redacted PHP port of Underscore.js with additional functions and goodies – Available for Composer and Laravel
Pros of underscore-php
- Broader functionality: Covers arrays, strings, objects, and more
- Inspired by Underscore.js, familiar to JavaScript developers
- Chainable methods for fluent API usage
Cons of underscore-php
- Less specialized for string manipulation compared to Stringy
- May include unnecessary functions for projects focused on string operations
- Potentially larger footprint due to its wide range of features
Code Comparison
Stringy:
use Stringy\Stringy as S;
$string = S::create('fòôbàř');
echo $string->toAscii(); // foobAr
underscore-php:
use Underscore\Types\Strings;
$string = Strings::create('fòôbàř');
echo Strings::toAscii($string); // foobAr
Both libraries offer string manipulation capabilities, but Stringy is more focused on string operations, while underscore-php provides a broader set of utilities. Stringy uses a more object-oriented approach, whereas underscore-php follows a functional programming style similar to its JavaScript counterpart. The choice between the two depends on project requirements and developer preferences.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
A PHP string manipulation library with multibyte support. Compatible with PHP 5.4+, PHP 7+, and HHVM.
s('string')->toTitleCase()->ensureRight('y') == 'Stringy'
Refer to the 1.x branch or 2.x branch for older documentation.
- Why?
- Installation
- OO and Chaining
- Implemented Interfaces
- PHP 5.6 Creation
- StaticStringy
- Class methods
- Instance methods
Why?
In part due to a lack of multibyte support (including UTF-8) across many of
PHP's standard string functions. But also to offer an OO wrapper around the
mbstring
module's multibyte-compatible functions. Stringy handles some quirks,
provides additional functionality, and hopefully makes strings a little easier
to work with!
// Standard library
strtoupper('fòôbà Å'); // 'FòôBà Å'
strlen('fòôbà Å'); // 10
// mbstring
mb_strtoupper('fòôbà Å'); // 'FÃÃBÃÅ'
mb_strlen('fòôbà Å'); // '6'
// Stringy
s('fòôbà Å')->toUpperCase(); // 'FÃÃBÃÅ'
s('fòôbà Å')->length(); // '6'
Installation
If you're using Composer to manage dependencies, you can include the following in your composer.json file:
"require": {
"danielstjules/stringy": "~3.1.0"
}
Then, after running composer update
or php composer.phar update
, you can
load the class using Composer's autoloading:
require 'vendor/autoload.php';
Otherwise, you can simply require the file directly:
require_once 'path/to/Stringy/src/Stringy.php';
And in either case, I'd suggest using an alias.
use Stringy\Stringy as S;
Please note that Stringy relies on the mbstring
module for its underlying
multibyte support. If the module is not found, Stringy will use
symfony/polyfill-mbstring.
ex-mbstring is a non-default, but very common module. For example, with debian
and ubuntu, it's included in libapache2-mod-php5, php5-cli, and php5-fpm. For
OSX users, it's a default for any version of PHP installed with homebrew.
If compiling PHP from scratch, it can be included with the
--enable-mbstring
flag.
OO and Chaining
The library offers OO method chaining, as seen below:
use Stringy\Stringy as S;
echo S::create('fòô bà Å')->collapseWhitespace()->swapCase(); // 'FÃà BÃÅ'
Stringy\Stringy
has a __toString() method, which returns the current string
when the object is used in a string context, ie:
(string) S::create('foo') // 'foo'
Implemented Interfaces
Stringy\Stringy
implements the IteratorAggregate
interface, meaning that
foreach
can be used with an instance of the class:
$stringy = S::create('fòôbà Å');
foreach ($stringy as $char) {
echo $char;
}
// 'fòôbà Å'
It implements the Countable
interface, enabling the use of count()
to
retrieve the number of characters in the string:
$stringy = S::create('fòô');
count($stringy); // 3
Furthermore, the ArrayAccess
interface has been implemented. As a result,
isset()
can be used to check if a character at a specific index exists. And
since Stringy\Stringy
is immutable, any call to offsetSet
or offsetUnset
will throw an exception. offsetGet
has been implemented, however, and accepts
both positive and negative indexes. Invalid indexes result in an
OutOfBoundsException
.
$stringy = S::create('bà Å');
echo $stringy[2]; // 'Å'
echo $stringy[-2]; // 'Ã '
isset($stringy[-4]); // false
$stringy[3]; // OutOfBoundsException
$stringy[2] = 'a'; // Exception
PHP 5.6 Creation
As of PHP 5.6, use function
is
available for importing functions. Stringy exposes a namespaced function,
Stringy\create
, which emits the same behaviour as Stringy\Stringy::create()
.
If running PHP 5.6, or another runtime that supports the use function
syntax,
you can take advantage of an even simpler API as seen below:
use function Stringy\create as s;
// Instead of: S::create('fòô bà Å')
s('fòô bà Å')->collapseWhitespace()->swapCase();
StaticStringy
All methods listed under "Instance methods" are available as part of a static wrapper. For StaticStringy methods, the optional encoding is expected to be the last argument. The return value is not cast, and may thus be of type Stringy, integer, boolean, etc.
use Stringy\StaticStringy as S;
// Translates to Stringy::create('fòôbà Å')->slice(0, 3);
// Returns a Stringy object with the string "fòô"
S::slice('fòôbà Å', 0, 3);
Class methods
create(mixed $str [, $encoding ])
Creates a Stringy object and assigns both str and encoding properties the supplied values. $str is cast to a string prior to assignment, and if $encoding is not specified, it defaults to mb_internal_encoding(). It then returns the initialized object. Throws an InvalidArgumentException if the first argument is an array or object without a __toString method.
$stringy = S::create('fòôbà Å'); // 'fòôbà Å'
Instance Methods
Stringy objects are immutable. All examples below make use of PHP 5.6 function importing, and PHP 5.4 short array syntax. They also assume the encoding returned by mb_internal_encoding() is UTF-8. For further details, see the documentation for the create method above, as well as the notes on PHP 5.6 creation.
append(string $string)
Returns a new string with $string appended.
s('fòô')->append('bà Å'); // 'fòôbà Å'
at(int $index)
Returns the character at $index, with indexes starting at 0.
s('fòôbà Å')->at(3); // 'b'
between(string $start, string $end [, int $offset])
Returns the substring between $start and $end, if found, or an empty string. An optional offset may be supplied from which to begin the search for the start string.
s('{foo} and {bar}')->between('{', '}'); // 'foo'
camelize()
Returns a camelCase version of the string. Trims surrounding spaces, capitalizes letters following digits, spaces, dashes and underscores, and removes spaces, dashes, as well as underscores.
s('Camel-Case')->camelize(); // 'camelCase'
chars()
Returns an array consisting of the characters in the string.
s('fòôbà Å')->chars(); // ['f', 'ò', 'ô', 'b', 'à ', 'Å']
collapseWhitespace()
Trims the string and replaces consecutive whitespace characters with a single space. This includes tabs and newline characters, as well as multibyte whitespace such as the thin space and ideographic space.
s(' Î ÏÏ
γγÏαÏÎÎ±Ï ')->collapseWhitespace(); // 'Î ÏÏ
γγÏαÏÎαÏ'
contains(string $needle [, boolean $caseSensitive = true ])
Returns true if the string contains $needle, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.
s('Î ÏÏ
γγÏαÏÎÎ±Ï ÎµÎ¯Ïε')->contains('ÏÏ
γγÏαÏÎαÏ'); // true
containsAll(array $needles [, boolean $caseSensitive = true ])
Returns true if the string contains all $needles, false otherwise. By default the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.
s('foo & bar')->containsAll(['foo', 'bar']); // true
containsAny(array $needles [, boolean $caseSensitive = true ])
Returns true if the string contains any $needles, false otherwise. By default the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.
s('str contains foo')->containsAny(['foo', 'bar']); // true
countSubstr(string $substring [, boolean $caseSensitive = true ])
Returns the number of occurrences of $substring in the given string. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.
s('Î ÏÏ
γγÏαÏÎÎ±Ï ÎµÎ¯Ïε')->countSubstr('α'); // 2
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.
s('fooBar')->dasherize(); // 'foo-bar'
delimit(int $delimiter)
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.
s('fooBar')->delimit('::'); // 'foo::bar'
endsWith(string $substring [, boolean $caseSensitive = true ])
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.
s('fòôbà Å')->endsWith('bà Å'); // true
endsWithAny(string[] $substrings [, boolean $caseSensitive = true ])
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.
s('fòôbà Å')->endsWithAny(['bà Å', 'baz']); // true
ensureLeft(string $substring)
Ensures that the string begins with $substring. If it doesn't, it's prepended.
s('foobar')->ensureLeft('http://'); // 'http://foobar'
ensureRight(string $substring)
Ensures that the string ends with $substring. If it doesn't, it's appended.
s('foobar')->ensureRight('.com'); // 'foobar.com'
first(int $n)
Returns the first $n characters of the string.
s('fòôbà Å')->first(3); // 'fòô'
getEncoding()
Returns the encoding used by the Stringy object.
s('fòôbà Å')->getEncoding(); // 'UTF-8'
hasLowerCase()
Returns true if the string contains a lower case char, false otherwise.
s('fòôbà Å')->hasLowerCase(); // true
hasUpperCase()
Returns true if the string contains an upper case char, false otherwise.
s('fòôbà Å')->hasUpperCase(); // false
htmlDecode()
Convert all HTML entities to their applicable characters. An alias of html_entity_decode. For a list of flags, refer to http://php.net/manual/en/function.html-entity-decode.php
s('&')->htmlDecode(); // '&'
htmlEncode()
Convert all applicable characters to HTML entities. An alias of htmlentities. Refer to http://php.net/manual/en/function.htmlentities.php for a list of flags.
s('&')->htmlEncode(); // '&'
humanize()
Capitalizes the first word of the string, replaces underscores with spaces, and strips '_id'.
s('author_id')->humanize(); // 'Author'
indexOf(string $needle [, $offset = 0 ]);
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. A negative index searches from the end
s('string')->indexOf('ing'); // 3
indexOfLast(string $needle [, $offset = 0 ]);
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.
s('foobarfoo')->indexOfLast('foo'); // 10
insert(int $index, string $substring)
Inserts $substring into the string at the $index provided.
s('fòôbÅ')->insert('à ', 4); // 'fòôbà Å'
isAlpha()
Returns true if the string contains only alphabetic chars, false otherwise.
s('丹尼ç¾')->isAlpha(); // true
isAlphanumeric()
Returns true if the string contains only alphabetic and numeric chars, false otherwise.
s('داÙÙاÙ1')->isAlphanumeric(); // true
isBase64()
Returns true if the string is base64 encoded, false otherwise.
s('Zm9vYmFy')->isBase64(); // true
isBlank()
Returns true if the string contains only whitespace chars, false otherwise.
s("\n\t \v\f")->isBlank(); // true
isHexadecimal()
Returns true if the string contains only hexadecimal chars, false otherwise.
s('A102F')->isHexadecimal(); // true
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.
s('{"foo":"bar"}')->isJson(); // true
isLowerCase()
Returns true if the string contains only lower case chars, false otherwise.
s('fòôbà Å')->isLowerCase(); // true
isSerialized()
Returns true if the string is serialized, false otherwise.
s('a:1:{s:3:"foo";s:3:"bar";}')->isSerialized(); // true
isUpperCase()
Returns true if the string contains only upper case chars, false otherwise.
s('FÃÃBÃÅ')->isUpperCase(); // true
last(int $n)
Returns the last $n characters of the string.
s('fòôbà Å')->last(3); // 'bà Å'
length()
Returns the length of the string. An alias for PHP's mb_strlen() function.
s('fòôbà Å')->length(); // 6
lines()
Splits on newlines and carriage returns, returning an array of Stringy objects corresponding to the lines in the string.
s("fòô\r\nbà Å\n")->lines(); // ['fòô', 'bà Å', '']
longestCommonPrefix(string $otherStr)
Returns the longest common prefix between the string and $otherStr.
s('foobar')->longestCommonPrefix('foobaz'); // 'fooba'
longestCommonSuffix(string $otherStr)
Returns the longest common suffix between the string and $otherStr.
s('fòôbà Å')->longestCommonSuffix('fòrbà Å'); // 'bà Å'
longestCommonSubstring(string $otherStr)
Returns the longest common substring between the string and $otherStr. In the case of ties, it returns that which occurs first.
s('foobar')->longestCommonSubstring('boofar'); // 'oo'
lowerCaseFirst()
Converts the first character of the supplied string to lower case.
s('Σ foo')->lowerCaseFirst(); // 'Ï foo'
pad(int $length [, string $padStr = ' ' [, string $padType = 'right' ]])
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.
s('fòôbà Å')->pad(9, '-/', 'left'); // '-/-fòôbà Å'
padBoth(int $length [, string $padStr = ' ' ])
Returns a new string of a given length such that both sides of the string string are padded. Alias for pad() with a $padType of 'both'.
s('foo bar')->padBoth(9, ' '); // ' foo bar '
padLeft(int $length [, string $padStr = ' ' ])
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'.
s('foo bar')->padLeft(9, ' '); // ' foo bar'
padRight(int $length [, string $padStr = ' ' ])
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'.
s('foo bar')->padRight(10, '_*'); // 'foo bar_*_'
prepend(string $string)
Returns a new string starting with $string.
s('bà Å')->prepend('fòô'); // 'fòôbà Å'
regexReplace(string $pattern, string $replacement [, string $options = 'msr'])
Replaces all occurrences of $pattern in $str by $replacement. An alias for mb_ereg_replace(). Note that the 'i' option with multibyte 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 < 5.6, and current versions of HHVM (3.8 and below).
s('fòô ')->regexReplace('f[òô]+\s', 'bà Å'); // 'bà Å'
s('fò')->regexReplace('(ò)', '\\1ô'); // 'fòô'
removeLeft(string $substring)
Returns a new string with the prefix $substring removed, if present.
s('fòôbà Å')->removeLeft('fòô'); // 'bà Å'
removeRight(string $substring)
Returns a new string with the suffix $substring removed, if present.
s('fòôbà Å')->removeRight('bà Å'); // 'fòô'
repeat(int $multiplier)
Returns a repeated string given a multiplier. An alias for str_repeat.
s('α')->repeat(3); // 'ααα'
replace(string $search, string $replacement)
Replaces all occurrences of $search in $str by $replacement.
s('fòô bà Šfòô bà Å')->replace('fòô ', ''); // 'bà Šbà Å'
reverse()
Returns a reversed string. A multibyte version of strrev().
s('fòôbà Å')->reverse(); // 'Åà bôòf'
safeTruncate(int $length [, string $substring = '' ])
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.
s('What are your plans today?')->safeTruncate(22, '...');
// 'What are your plans...'
shuffle()
A multibyte str_shuffle() function. It returns a string with its characters in random order.
s('fòôbà Å')->shuffle(); // 'à ôÅbòf'
slugify([, string $replacement = '-' [, string $language = 'en']])
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.
s('Using strings like fòô bà Å')->slugify(); // 'using-strings-like-foo-bar'
slice(int $start [, int $end ])
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.
s('fòôbà Å')->slice(3, -1); // 'bà '
split(string $pattern [, int $limit ])
Splits the string with the provided regular expression, returning an array of Stringy objects. An optional integer $limit will truncate the results.
s('foo,bar,baz')->split(',', 2); // ['foo', 'bar']
startsWith(string $substring [, boolean $caseSensitive = true ])
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.
s('FÃÃbà Åbaz')->startsWith('fòôbà Å', false); // true
startsWithAny(string[] $substrings [, boolean $caseSensitive = true ])
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.
s('FÃÃbà Åbaz')->startsWithAny(['fòô', 'bà Å'], false); // true
stripWhitespace()
Strip all whitespace characters. This includes tabs and newline characters, as well as multibyte whitespace such as the thin space and ideographic space.
s(' Î ÏÏ
γγÏαÏÎÎ±Ï ')->stripWhitespace(); // 'ÎÏÏ
γγÏαÏÎαÏ'
substr(int $start [, int $length ])
Returns the substring beginning at $start with the specified $length. It differs from the mb_substr() function in that providing a $length of null will return the rest of the string, rather than an empty string.
s('fòôbà Å')->substr(2, 3); // 'ôbà '
surround(string $substring)
Surrounds a string with the given substring.
s(' Í ')->surround('Ê'); // 'Ê Í Ê'
swapCase()
Returns a case swapped version of the string.
s('ÎÏανιλ')->swapCase(); // 'νΤÎÎÎÎ'
tidy()
Returns a string with smart quotes, ellipsis characters, and dashes from Windows-1252 (commonly used in Word documents) replaced by their ASCII equivalents.
s('âI seeâ¦â')->tidy(); // '"I see..."'
titleize([, array $ignore])
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.
$ignore = ['at', 'by', 'for', 'in', 'of', 'on', 'out', 'to', 'the'];
s('i like to watch television')->titleize($ignore);
// 'I Like to Watch Television'
toAscii([, string $language = 'en' [, bool $removeUnsupported = true ]])
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.
s('fòôbà Å')->toAscii(); // 'foobar'
s('äöü')->toAscii(); // 'aou'
s('äöü')->toAscii('de'); // 'aeoeue'
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.
s('OFF')->toBoolean(); // false
toLowerCase()
Converts all characters in the string to lowercase. An alias for PHP's mb_strtolower().
s('FÃÃBÃÅ')->toLowerCase(); // 'fòôbà Å'
toSpaces([, tabLength = 4 ])
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.
s(' String speech = "Hi"')->toSpaces(); // ' String speech = "Hi"'
toTabs([, tabLength = 4 ])
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.
s(' fòô bà Å')->toTabs();
// ' fòô bà Å'
toTitleCase()
Converts the first character of each word in the string to uppercase.
s('fòô bà Å')->toTitleCase(); // 'Fòô Bà Å'
toUpperCase()
Converts all characters in the string to uppercase. An alias for PHP's mb_strtoupper().
s('fòôbà Å')->toUpperCase(); // 'FÃÃBÃÅ'
trim([, string $chars])
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.
s(' fòôbà Š')->trim(); // 'fòôbà Å'
trimLeft([, string $chars])
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.
s(' fòôbà Š')->trimLeft(); // 'fòôbà Š'
trimRight([, string $chars])
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.
s(' fòôbà Š')->trimRight(); // ' fòôbà Å'
truncate(int $length [, string $substring = '' ])
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.
s('What are your plans today?')->truncate(19, '...'); // 'What are your pl...'
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.
s('TestUCase')->underscored(); // 'test_u_case'
upperCamelize()
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.
s('Upper Camel-Case')->upperCamelize(); // 'UpperCamelCase'
upperCaseFirst()
Converts the first character of the supplied string to upper case.
s('Ï foo')->upperCaseFirst(); // 'Σ foo'
Extensions
The following is a list of libraries that extend Stringy:
- SliceableStringy: Python-like string slices in PHP
- SubStringy: Advanced substring methods
Tests
From the project directory, tests can be ran using phpunit
License
Released under the MIT License - see LICENSE.txt
for details.
Top Related Projects
Doctrine Inflector is a small library that can perform string manipulations with regard to uppercase/lowercase and singular/plural forms of words.
Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way
:snowflake: A PHP library for generating universally unique identifiers (UUIDs).
A redacted PHP port of Underscore.js with additional functions and goodies – Available for Composer and Laravel
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot