You are browsing the unmaintained documentation for old Nette 2.2. See documentation for current Nette.

String Functions

Nette\Utils\Strings is a static class, which contains many useful functions for working with UTF-8 encoded strings.


composer require nette/utils

All examples assume the following class alias is defined:

use Nette\Utils\Strings;

Letter Case

Requires PHP extension mbstring.

lower(string $s): string

Converts all characters of UTF-8 string to lower case.

Strings::lower('Hello world'); // 'hello world'

upper(string $s): string

Converts all characters of a UTF-8 string to upper case.

Strings::upper('Hello world'); // 'HELLO WORLD'

firstUpper(string $s): string

Converts the first character of a UTF-8 string to upper case and leaves the other characters unchanged.

Strings::firstUpper('hello world'); // 'Hello world'

capitalize(string $s): string

Converts the first character of every word of a UTF-8 string to upper case and the others to lower case.

Strings::capitalize('Hello world'); // 'Hello World'

Editing a String

normalize(string $s): string

Removes control characters, normalizes line breaks to \n, removes leading and trailing blank lines, trims end spaces on lines, normalizes UTF-8 to the normal form of NFC.

webalize(string $s, string $charlist=NULL, bool $lower=TRUE)string

Modifies the UTF-8 string to the form used in the URL, ie removes diacritics and replaces all characters except letters of the English alphabet and numbers with a hyphens.

Strings::webalize('žluťoučký kůň'); // 'zlutoucky-kun'

Other characters may be preserved as well, but they must be passed as second argument.

Strings::webalize('10. image_id', '._'); // '10.-image_id'

The third argument may suppress converting the string to lower case.

Strings::webalize('Hello world', NULL, FALSE); // 'Hello-world'

trim(string $s, string $charlist=NULL)string

Removes all left and right side spaces (or the characters passed as second argument) from a UTF-8 encoded string.

Strings::trim('  Hello  '); // 'Hello'

truncate(string $s, int $maxLen, string $append=`'…'`)string

Truncates a UTF-8 string to given maximal length, while trying not to split whole words. Only if the string is truncated, an ellipsis (or something else set with third argument) is appended to the string.

$text = 'Hello, how are you today?';
Strings::truncate($text, 5);       // 'Hell…'
Strings::truncate($text, 20);      // 'Hello, how are you…'
Strings::truncate($text, 30);      // 'Hello, how are you today?'
Strings::truncate($text, 20, '~'); // 'Hello, how are you~'

indent(string $s, int $level=1, string $indentationChar=`"\t"`)string

Indents a multiline text from the left. Second argument sets how many indentation chars should be used, while the indent itself is the third argument (tab by default).

Strings::indent('Nette');         // "\tNette"
Strings::indent('Nette', 2, '+'); // '++Nette'

padLeft(string $s, int $length, string $pad=`' '`)string

Pads a UTF-8 string to given length by prepending the $pad string to the beginning.

Strings::padLeft('Nette', 6);        // ' Nette'
Strings::padLeft('Nette', 8, '+*');  // '+*+Nette'

padRight(string $s, int $length, string $pad=`' '`)string

Pads UTF-8 string to given length by appending the $pad string to the end.

Strings::padRight('Nette', 6);       // 'Nette '
Strings::padRight('Nette', 8, '+*'); // 'Nette+*+'

substring(string $s, int $start, int $length=NULL)string

Returns a part of UTF-8 string specified by starting position $start and length $length. If $start is negative, the returned string will start at the $start'th character from the end of string.

Strings::substring('Nette Framework', 0, 5); // 'Nette'
Strings::substring('Nette Framework', 6);    // 'Framework'
Strings::substring('Nette Framework', -4);   // 'work'

normalizeNewLines(string $s)string

Standardize line endings to unix-like.

$unixLikeLines = Strings::normalizeNewLines($string);

reverse(string $s): string

Reverses UTF-8 string.

Strings::reverse('Nette'); // 'etteN'

length(string $s): int

Returns number of characters (not bytes) in UTF-8 string.

That is the number of Unicode code points which may differ from the number of graphemes.

Strings::length('Nette'); // 5
Strings::length('red');   // 3

startsWith(string $haystack, string $needle)bool

Returns TRUE if $haystack string begins with $needle.

$haystack = 'Begins';
$needle = 'Be';
Strings::startsWith($haystack, $needle); // TRUE

endsWith(string $haystack, string $needle)bool

Returns TRUE if $haystack string end with $needle.

$haystack = 'Ends';
$needle = 'ds';
Strings::endsWith($haystack, $needle); // TRUE

contains(string $haystack, string $needle)bool

Returns TRUE if $haystack string contains $needle.

$haystack = 'Contains';
$needle = 'tai';
Strings::contains($haystack, $needle); // TRUE

compare(string $left, string $right, int $length=NULL)bool

Compares two UTF-8 strings or their parts, without taking character case into account. If $length is NULL, whole strings are compared, if it is negative, the corresponding number of characters from the end of the strings is compared, otherwise the appropriate number of characters from the beginning is compared.

Strings::compare('Nette', 'nette');     // TRUE
Strings::compare('Nette', 'next', 2);   // TRUE - two first characters match
Strings::compare('Nette', 'Latte', -2); // TRUE - two last characters match

findPrefix(…$strings): string

Finds the common prefix of strings or returns empty string if the prefix was not found.

Strings::findPrefix('prefix-a', 'prefix-bb', 'prefix-c');   // 'prefix-'
Strings::findPrefix(array('prefix-a', 'prefix-bb', 'prefix-c')); // 'prefix-'
Strings::findPrefix('Nette', 'is', 'great');                // ''


fixEncoding(string $s): string

Removes all invalid UTF-8 characters from a string.

$correctStrings = Strings::fixEncoding($string);

checkEncoding(string $s)bool

Checks if the string is valid in UTF-8 encoding.

$isUtf8 = Strings::checkEncoding($string);

toAscii(string $s): string

Converts UTF-8 string to ASCII, ie removes diacritics etc.

Strings::toAscii('žluťoučký kůň'); // 'zlutoucky kun'

chr(int $code): string

Returns a specific character in UTF-8 from code point (number in range 0×0000..D7FF or 0×E000..10FFFF).

Strings::chr(0xA9); // '©'

Regular Expressions

Class Strings contains a few methods for working with regular expressions. Unlike native php functions, it provides readable API and throws Nette\RegexpException if any regexp error occurs.

split(string $subject, string $pattern, int $flags=NULL)array

Splits a string into array by the regular expression. Argument $flag takes same arguments as preg_split, but PREG_SPLIT_DELIM_CAPTURE is set by default.

$res = Strings::split('One,  two,three', '~,\s*~');
// array('One', 'two', 'three')
$res = Strings::split('One,  two,three', '~(,)\s*~');
// array('One', ',', 'two', ',', 'three')

match(string $subject, string $pattern, int $flags=NULL, int $offset=0)array

Checks if given string matches a regular expression and returns an array with first found match and each subpattern. Argument $flag takes same arguments as function preg_match.

The optional parameter $offset can be used to specify the alternate place from which to start the search (in bytes, not in characters!).

list($res) = Strings::match('One,  two,three', '~[a-z]+~i'); // 'One'
list($res) = Strings::match('One,  two,three', '~\d+~'); // NULL

matchAll(string $subject, string $pattern, int $flags=NULL, int $offset=0)array

Finds all occurrences matching regular expression pattern and returns a two-dimensional array. Argument $flag takes same arguments as function preg_match_all, but PREG_SET_ORDER is set by default.

The optional parameter $offset can be used to specify the alternate place from which to start the search (in bytes, not in characters!).

$res = Strings::matchAll('One,  two,tree', '~[a-z]+~i');
	0 => array('One'),
	1 => array('two'),
	2 => array('three'),

$res = Strings::matchAll('One,  two,three', '~\d+~'); // []

replace(string $subject, string|array $pattern, string|callable $replacement=NULL, int $limit=-1)string

Replaces all occurrences matching regular expression $pattern which can be string or array in the form pattern =>` replacement`. The third argument is a replacement string or a callback and the fourth limits the count of replacements.

Strings::replace('One, two,three', '~[a-z]+~i', '*');
// '*,  *,*'

Strings::replace('One,  two,three', array(
	'~[a-z]+~i' => '*',
	'~\s+~' => '+',
// '*,+*,*'

Strings::replace('One,  two,three', '~[a-z]+~i', function ($m) {
	return strrev($m[0]);
// 'enO,  owt,eerht'

Related blog posts