Text

String helpers for searching, trimming, splitting, joining, formatting, hashing, and encoding or decoding text, grouped into a small set of static classes.

This page is a pure reference. For how the framework fits together, see the Guide.

Classes
  • Text - the main string library: searching, trimming, splitting, formatting and random strings.
  • TextDecode - decode text from JSON or base64.
  • TextDecodeError - thrown when text cannot be decoded.
  • TextEncode - encode values for HTML, URLs, JSON, SQL and the shell.
  • TextHash - hash a string with SHA-256.
  • TextUrl - read parts of a slash-separated URL path.

Text

The main string library. Static functions for measuring, comparing, joining, trimming, searching, splitting, formatting and generating strings. Character-set constants below describe the allowed characters used by helpers such as AllowChars and ContainsOnly.

Constants

ConstantValueDescription
Text::CHARS_UPPER'ABCDEFGHIJKLMNOPQRSTUVWXYZ'The uppercase letters.
Text::CHARS_LOWER'abcdefghijklmnopqrstuvwxyz'The lowercase letters.
Text::CHARS_NUMERIC'0123456789'The decimal digits.
Text::CHARS_ALPHANUMERIC'A-Za-z0-9'Letters and digits.
Text::CHARS_ALPHA'A-Za-z'Upper and lowercase letters.
Text::CHARS_URLNAME'A-Za-z0-9-._'Characters allowed in a URL name.
Text::CHARS_FILENAME'A-Za-z0-9 and punctuation'Characters allowed in a file name.
Text::DATABASE_NAME_CHARS'A-Za-z_0-9'Characters allowed in a database name.
Text::CHARS_DOMAINNAME'a-z0-9-.'Characters allowed in a domain name.
Text::CHARS_EMAIL'A-Za-z0-9-+_.@'Characters allowed in an email address.
Text::CHARS_HEX'ABCDEFabcdef0123456789'The hexadecimal digits.

AllowChars

Text::AllowChars($string, $allowed_chars)

Return the string with every character not in the allowed set removed.

NameTypeDescription
$stringstringThe string to filter.
$allowed_charsstringThe characters that are kept.

Returns string The filtered string.

Append

Text::Append(string $a, string $b): string

Join two strings together.

NameTypeDescription
$astringThe first string.
$bstringThe second string.

Returns string The two strings joined.

Append3

Text::Append3(string $a, string $b, string $c): string

Join three strings together.

NameTypeDescription
$astringThe first string.
$bstringThe second string.
$cstringThe third string.

Returns string The three strings joined.

Append4

Text::Append4(string $a, string $b, string $c, string $d): string

Join four strings together.

NameTypeDescription
$astringThe first string.
$bstringThe second string.
$cstringThe third string.
$dstringThe fourth string.

Returns string The four strings joined.

Append5

Text::Append5(string $a, string $b, string $c, string $d, string $e): string

Join five strings together.

NameTypeDescription
$astringThe first string.
$bstringThe second string.
$cstringThe third string.
$dstringThe fourth string.
$estringThe fifth string.

Returns string The five strings joined.

Append6

Text::Append6(string $a, string $b, string $c, string $d, string $e, string $f): string

Join six strings together.

NameTypeDescription
$astringThe first string.
$bstringThe second string.
$cstringThe third string.
$dstringThe fourth string.
$estringThe fifth string.
$fstringThe sixth string.

Returns string The six strings joined.

Append7

Text::Append7(string $a, string $b, string $c, string $d, string $e, string $f, string $g): string

Join seven strings together.

NameTypeDescription
$astringThe first string.
$bstringThe second string.
$cstringThe third string.
$dstringThe fourth string.
$estringThe fifth string.
$fstringThe sixth string.
$gstringThe seventh string.

Returns string The seven strings joined.

AppendOptional

Text::AppendOptional(string $text, ?string $optionalText): string

Append the optional string when it is not null, otherwise return the base string unchanged.

NameTypeDescription
$textstringThe base string.
$optionalText?stringThe string to append, or null.

Returns string The result.

ChangeIndents

Text::ChangeIndents($text, $change, $tab_size = 4)

Add or remove leading spaces on every line, after expanding tabs.

NameTypeDescription
$textstringThe text to reindent.
$changeintSpaces to add, or a negative number to remove.
$tab_sizeintSpaces a tab expands to (default 4).

Returns string The reindented text.

CharAt

Text::CharAt($text, $pos, $default = '')

Return the single character at a position, or a default when the position is past the end.

NameTypeDescription
$textstringThe string to read from.
$posintThe character position.
$defaultstringReturned when the position is out of range.

Returns string The character, or the default.

CheckSaltedSHA1

Text::CheckSaltedSHA1(string $salted_sha1, string $string_to_check, int $salt_length = 8): bool

Check a string against a salted SHA-1 value produced by SaltedSHA1.

NameTypeDescription
$salted_sha1stringThe salted hash to check against.
$string_to_checkstringThe candidate string.
$salt_lengthintLength of the salt prefix (default 8).

Returns bool True when the string matches.

Contains

Text::Contains(string $haystack, string $needle): bool

Whether the haystack contains the needle.

NameTypeDescription
$haystackstringThe string to search in.
$needlestringThe substring to look for.

Returns bool True when the needle is present.

ContainsOnly

Text::ContainsOnly(string $string, string $allowed_chars): bool

Whether the string is made up only of allowed characters.

NameTypeDescription
$stringstringThe string to test.
$allowed_charsstringThe set of permitted characters.

Returns bool True when nothing was filtered out.

DecodeJson

Text::DecodeJson(&$json_text)

Decode a JSON string, returning null when decoding fails.

NameTypeDescription
$json_textstringThe JSON text to decode.

Returns mixed The decoded value, or null.

Elipsis

Text::Elipsis(string $string, int $maxLength): string

Alias of TruncateEllipsis: shorten a string and add an ellipsis when it is too long.

NameTypeDescription
$stringstringThe string to shorten.
$maxLengthintThe maximum length before truncation.

Returns string The possibly truncated string.

Empty

Text::Empty(string $text): bool

Whether the string is the empty string.

NameTypeDescription
$textstringThe string to test.

Returns bool True when the string is empty.

EndsWith

Text::EndsWith(string $haystack, string $needle): bool

Whether the haystack ends with the needle.

NameTypeDescription
$haystackstringThe string to test.
$needlestringThe suffix to look for.

Returns bool True when it ends with the needle.

EnsureStartsWith

Text::EnsureStartsWith(string $text, string $startsWith): string

Return the string with the given prefix added when it is not already present.

NameTypeDescription
$textstringThe string to check.
$startsWithstringThe prefix to ensure.

Returns string The string, guaranteed to start with the prefix.

Equal

Text::Equal(string $a, string $b): bool

Whether two strings are identical.

NameTypeDescription
$astringThe first string.
$bstringThe second string.

Returns bool True when the strings are equal.

ExplodePath

Text::ExplodePath(string $path): array

Split a leading-slash path into its segments, dropping the empty leading part.

NameTypeDescription
$pathstringThe path to split.

Returns array The path segments.

FileExtension

Text::FileExtension(string $filename): string

The file extension after the last dot, or the empty string when there is none.

NameTypeDescription
$filenamestringThe file name.

Returns string The extension, without the dot.

FormatNumber

Text::FormatNumber($n, $decimal_places = 0, $add_thousands_sep = true)

Format a number with a fixed or optional number of decimal places and optional thousands separators.

NameTypeDescription
$nmixedThe number to format.
$decimal_placesintDecimal places; a negative value makes them optional.
$add_thousands_sepboolWhether to add thousands separators.

Returns string The formatted number.

FromJson

Text::FromJson($json)

Return the JSON string after checking it is a string.

NameTypeDescription
$jsonstringThe JSON string.

Returns string The JSON string.

GetBetween

Text::GetBetween(string $text, string $a, string $b): string|null

The text between the first occurrence of one marker and the next occurrence of another.

NameTypeDescription
$textstringThe text to search.
$astringThe start marker.
$bstringThe end marker.

Returns string|null The text between, or null when the start marker is missing.

GetBetweenLast

Text::GetBetweenLast(string $text, string $a, string $b): string

The text between the last occurrence of one marker and the last occurrence of another.

NameTypeDescription
$textstringThe text to search.
$astringThe start marker.
$bstringThe end marker.

Returns string The text between, or the empty string.

GetEverythingAfter

Text::GetEverythingAfter($str, $substr)

Everything after the first occurrence of a substring, or null when it is not found.

NameTypeDescription
$strstringThe string to search.
$substrstringThe substring to find.

Returns string|null The text after the substring, or null.

GetEverythingAfterOptional

Text::GetEverythingAfterOptional(string $str, string $substr): ?string

Everything after the first occurrence of a substring, or null when it is not found.

NameTypeDescription
$strstringThe string to search.
$substrstringThe substring to find.

Returns ?string The text after the substring, or null.

GetEverythingBefore

Text::GetEverythingBefore(string $haystack, string $needle): string

Everything before the first occurrence of a substring.

NameTypeDescription
$haystackstringThe string to search.
$needlestringThe substring to find.

Returns string The text before the substring.

GetIndent

Text::GetIndent($line, $tab_size = 4)

The number of leading whitespace characters on a line, after expanding tabs.

NameTypeDescription
$linestringThe line to measure.
$tab_sizeintSpaces a tab expands to (default 4).

Returns int The indent size, in characters.

GetLineAndChar

Text::GetLineAndChar($text, $pos)

The line number and character position for a character offset in the text.

NameTypeDescription
$textstringThe text to inspect.
$posintThe character offset.

Returns array A two-item array of line number and character number.

GetLines

Text::GetLines(string &$text, bool $removeBlanks = false): array

Split text into lines, normalising line endings and optionally dropping blank lines.

NameTypeDescription
$textstringThe text to split.
$removeBlanksboolWhether to drop blank lines.

Returns array The lines.

GetStringsBetween

Text::GetStringsBetween($haystack, $a, $b)

Every piece of text found between each pair of markers.

NameTypeDescription
$haystackstringThe text to search.
$astringThe start marker.
$bstringThe end marker.

Returns array The matched pieces.

GetStringsOutside

Text::GetStringsOutside(&$haystack, $a, $b)

The pieces of text lying outside each pair of markers.

NameTypeDescription
$haystackstringThe text to search.
$astringThe start marker.
$bstringThe end marker.

Returns array The pieces outside the markers.

IndexOf

Text::IndexOf(&$haystack, $needle, $offset = 0)

The position of the first occurrence of the needle, or -1 when it is not found.

NameTypeDescription
$haystackstringThe string to search.
$needlestringThe substring to find.
$offsetintThe position to start searching from.

Returns int The position, or -1.

IsLower

Text::IsLower(string $text): bool

Whether the string consists only of lowercase letters.

NameTypeDescription
$textstringThe string to test.

Returns bool True when it is all lowercase letters.

IsWhitespace

Text::IsWhitespace(string $text): bool

Whether the string is empty or only whitespace.

NameTypeDescription
$textstringThe string to test.

Returns bool True when it is all whitespace.

Join

Text::Join(&$elements, $separator = '')

Join an array of strings with a separator.

NameTypeDescription
$elementsarrayThe strings to join.
$separatorstringThe separator placed between them.

Returns string The joined string.

Length

Text::Length(string $text): int

The length of the string in bytes.

NameTypeDescription
$textstringThe string to measure.

Returns int The length.

Lower

Text::Lower($text)

The string converted to lowercase.

NameTypeDescription
$textstringThe string to convert.

Returns string The lowercase string.

LowerOptional

Text::LowerOptional(?string $text): ?string

The string converted to lowercase, or null when the input is null.

NameTypeDescription
$text?stringThe string to convert, or null.

Returns ?string The lowercase string, or null.

MakePath

Text::MakePath(array $bits): string

Join path segments with slashes into a leading-slash path.

NameTypeDescription
$bitsarrayThe path segments.

Returns string The joined path.

Matches

Text::Matches(array $haystack, array $pattern): array

Run a regular expression match and return the captured groups with offsets.

NameTypeDescription
$haystackarrayThe subject to match against.
$patternarrayThe pattern to match.

Returns array The matches.

NormalizePhoneNumber

Text::NormalizePhoneNumber(string $phone): string

Normalise a phone number to the 00 prefix form, converting a leading plus sign.

NameTypeDescription
$phonestringThe phone number in plus or 00 form.

Returns string The normalised number.

NotEmpty

Text::NotEmpty(string $text): bool

Whether the string is not the empty string.

NameTypeDescription
$textstringThe string to test.

Returns bool True when the string is not empty.

PadLeft

Text::PadLeft(string $string, int $length, string $padString = ' '): string

Pad a string on the left to a given length.

NameTypeDescription
$stringstringThe string to pad.
$lengthintThe desired length.
$padStringstringThe padding string (default a space).

Returns string The padded string.

RandomHexString

Text::RandomHexString(int $length = 16): string

A random hexadecimal string of the requested length.

NameTypeDescription
$lengthintThe number of hex characters (default 16).

Returns string The random hex string.

RandomMD5

Text::RandomMD5(string $seed = '...'): string

A random SHA-1 hash seeded with entropy, the current time and a random number.

NameTypeDescription
$seedstringExtra entropy mixed into the hash.

Returns string The random hash.

RandomSHA1

Text::RandomSHA1(string $seed = '...'): string

A random SHA-1 hash built from the seed and repeated entropy.

NameTypeDescription
$seedstringExtra entropy mixed into the hash.

Returns string The random hash.

RemoveChars

Text::RemoveChars($text, $num)

Remove characters from the front, or from the end when the count is negative.

NameTypeDescription
$textstringThe string to trim.
$numintCharacters to remove; negative removes from the end.

Returns string The trimmed string.

RemoveEverythingBetween

Text::RemoveEverythingBetween(&$text, $start, $end)

Remove every span of text between each pair of markers, keeping the rest.

NameTypeDescription
$textstringThe text to filter.
$startstringThe start marker.
$endstringThe end marker.

Returns string The text with the spans removed.

RemoveFromEnd

Text::RemoveFromEnd(string $haystack, string $needle): string

Remove the suffix from the string when it is present.

NameTypeDescription
$haystackstringThe string to trim.
$needlestringThe suffix to remove.

Returns string The string without the suffix.

RemoveFromStart

Text::RemoveFromStart(string $haystack, string $needle): string

Remove the prefix from the string when it is present.

NameTypeDescription
$haystackstringThe string to trim.
$needlestringThe prefix to remove.

Returns string The string without the prefix.

Replace

Text::Replace($search, $replace, $haystack)

Replace every occurrence of the search string with the replacement.

NameTypeDescription
$searchstringThe string to look for.
$replacestringThe replacement string.
$haystackstringThe string to search in.

Returns string The result.

ReplaceAll

Text::ReplaceAll($search, $replace, $haystack)

Repeatedly replace the search string until none remain, so overlapping matches are also removed.

NameTypeDescription
$searchstringThe string to look for.
$replacestringThe replacement string.
$haystackstringThe string to search in.

Returns string The result.

SaltedSHA1

Text::SaltedSHA1(string $text, string $entropy = '...'): string

Produce a salted SHA-1 value for a string that CheckSaltedSHA1 can verify.

NameTypeDescription
$textstringThe string to hash.
$entropystringExtra entropy for the salt.

Returns string The salt followed by the hash.

Split

Text::Split(string $string, string $delimiter, int $limit = null, bool $pad_with_default_value = false, string $default_value = ''): array

Split a string on a delimiter, optionally limiting and padding the result.

NameTypeDescription
$stringstringThe string to split.
$delimiterstringThe delimiter to split on.
$limitintThe maximum number of parts, or null.
$pad_with_default_valueboolWhether to pad up to the limit.
$default_valuestringThe value used for padding.

Returns array The parts.

SplitURL

Text::SplitURL(string $url): bool

Split a URL into its protocol, site, path, query arguments and anchor.

NameTypeDescription
$urlstringThe URL to split.

Returns array The protocol, site, path, arguments and anchor.

Start

Text::Start(string $text, int $length): string

The first characters of the string, up to the given length.

NameTypeDescription
$textstringThe string to read from.
$lengthintThe number of characters.

Returns string The starting characters.

StartsWith

Text::StartsWith(string $text, string $startsWith): bool

Whether the string begins with the given prefix.

NameTypeDescription
$textstringThe string to test.
$startsWithstringThe prefix to look for.

Returns bool True when it begins with the prefix.

Substring

Text::Substring(string $string, int $start, $length = null)

A substring from a start position, optionally limited to a length.

NameTypeDescription
$stringstringThe string to read from.
$startintThe start position.
$lengthintThe number of characters, or null for the rest.

Returns string The substring.

Trim

Text::Trim($text, $char = null)

Trim whitespace, or the given characters, from both ends of the string.

NameTypeDescription
$textstringThe string to trim.
$charstringCharacters to trim, or null for whitespace.

Returns string The trimmed string.

TrimBlankLines

Text::TrimBlankLines($text)

Remove blank lines from the start, and trailing whitespace, keeping the first non-blank line's indent.

NameTypeDescription
$textstringThe text to trim.

Returns string The trimmed text.

TrimEnd

Text::TrimEnd(string $text, string $char): string

Trim the given characters from the end of the string.

NameTypeDescription
$textstringThe string to trim.
$charstringThe characters to trim from the end.

Returns string The trimmed string.

TrimStart

Text::TrimStart($text, $char = null)

Trim whitespace, or the given characters, from the start of the string.

NameTypeDescription
$textstringThe string to trim.
$charstringCharacters to trim, or null for whitespace.

Returns string The trimmed string.

TruncateEllipsis

Text::TruncateEllipsis(string $string, int $maxLength): string

Shorten a string and add an ellipsis when it is longer than the maximum length.

NameTypeDescription
$stringstringThe string to shorten.
$maxLengthintThe maximum length before truncation.

Returns string The possibly truncated string.

Upper

Text::Upper($text)

The string converted to uppercase.

NameTypeDescription
$textstringThe string to convert.

Returns string The uppercase string.

UpperFirst

Text::UpperFirst($text)

The string with the first letter of each word capitalised.

NameTypeDescription
$textstringThe string to convert.

Returns string The converted string.

TextDecode

Decode text into values: parse JSON, parse JSON without throwing, or decode base64.

Base64

TextDecode::Base64(string $text): string

Decode a base64 string, first stripping surrounding quotes when present.

NameTypeDescription
$textstringThe base64 string, possibly wrapped in quotes.

Returns string The decoded string.

JSON

TextDecode::JSON(string $text, Callable|null $optionalCallback = null): mixed

Decode JSON text, optionally passing the result through a callback, and throw when it cannot be decoded.

NameTypeDescription
$textstringThe JSON text to decode.
$optionalCallbackCallable|nullA callback applied to the decoded value, or null.

Returns mixed The decoded value, or the callback result.

OptionalJson

TextDecode::OptionalJson(string $text): mixed

Decode JSON text, returning null instead of throwing when it cannot be decoded.

NameTypeDescription
$textstringThe JSON text to decode.

Returns mixed The decoded value, or null.

TextDecodeError

An exception thrown by TextDecode::JSON when the given text cannot be decoded. Extends the built-in Exception and adds no members of its own.

TextEncode

Encode values safely for a destination context: HTML, URLs, JSON, SQL identifiers and numbers, paths, and shell arguments and commands.

Html

TextEncode::Html($text): string

Escape a value for safe inclusion in HTML.

NameTypeDescription
$textmixedThe value to escape.

Returns string The HTML-escaped string.

HtmlJavaScript

TextEncode::HtmlJavaScript(string $javaScript): string

Return JavaScript for inclusion in an HTML page.

NameTypeDescription
$javaScriptstringThe JavaScript source.

Returns string The JavaScript.

HtmlNum

TextEncode::HtmlNum($value): string

Encode a numeric value for HTML.

NameTypeDescription
$valuemixedThe value to encode as a number.

Returns string The encoded number.

HtmlUrl

TextEncode::HtmlUrl($text): string

URL-encode a value and then HTML-escape it.

NameTypeDescription
$textmixedThe value to encode.

Returns string The encoded string.

HtmlUrlArray

TextEncode::HtmlUrlArray($array): string

Encode an array as a URL query string and then HTML-escape it.

NameTypeDescription
$arrayarrayThe name-to-value map.

Returns string The encoded query string.

Json

TextEncode::Json($data): string

Encode a value as JSON.

NameTypeDescription
$datamixedThe value to encode.

Returns string The JSON string.

JsonBoolean

TextEncode::JsonBoolean($data): string

Encode a value as a JSON boolean.

NameTypeDescription
$datamixedThe value to encode as a boolean.

Returns string The JSON boolean.

JsonNum

TextEncode::JsonNum($data, $min = null, $max = null): string

Encode a value as a JSON number, within optional bounds.

NameTypeDescription
$datamixedThe value to encode as a number.
$minmixedThe minimum allowed value, or null.
$maxmixedThe maximum allowed value, or null.

Returns string The JSON number.

JsonStr

TextEncode::JsonStr($data): string

Encode a value as a JSON string.

NameTypeDescription
$datamixedThe value to encode as a string.

Returns string The JSON string.

PathDate

TextEncode::PathDate($date): string

Encode a date for use in a path.

NameTypeDescription
$datemixedThe date to encode.

Returns string The encoded date.

PathID

TextEncode::PathID($id): int

Encode an id for use in a path.

NameTypeDescription
$idmixedThe id to encode.

Returns int The encoded id.

ShellArgument

TextEncode::ShellArgument(string $text): string

Escape a string so it is safe as a single shell argument.

NameTypeDescription
$textstringThe argument to escape.

Returns string The escaped argument.

ShellCommand

TextEncode::ShellCommand(string $text): string

Escape a string so it is safe as a shell command.

NameTypeDescription
$textstringThe command to escape.

Returns string The escaped command.

SqlDatabaseName

TextEncode::SqlDatabaseName($text): string

Validate and return a value safe to use as a SQL database name.

NameTypeDescription
$textmixedThe database name.

Returns string The database name.

SqlID

TextEncode::SqlID($id): int

Convert a value to an id safe to use in SQL.

NameTypeDescription
$idmixedThe id to convert.

Returns int The id.

SqlNum

TextEncode::SqlNum($id): int

Convert a value to a number safe to use in SQL.

NameTypeDescription
$idmixedThe value to convert.

Returns int The number.

SqlNumArray

TextEncode::SqlNumArray(array $array): array

Convert every element of an array to a SQL-safe number.

NameTypeDescription
$arrayarrayThe values to convert.

Returns array The converted numbers.

Url

TextEncode::Url($text): string

URL-encode a value.

NameTypeDescription
$textmixedThe value to encode.

Returns string The URL-encoded string.

UrlArray

TextEncode::UrlArray($array): string

Encode an array as a URL query string.

NameTypeDescription
$arrayarrayThe name-to-value map.

Returns string The query string.

UrlID

TextEncode::UrlID($value): int

Encode an id for use in a URL.

NameTypeDescription
$valuemixedThe id to encode.

Returns int The encoded id.

UrlNum

TextEncode::UrlNum($value): string

Encode a number for use in a URL.

NameTypeDescription
$valuemixedThe value to encode as a number.

Returns string The encoded number.

TextHash

Hash a string with SHA-256.

Functions

Sha256

TextHash::Sha256(string $string, int $length = 64): string

The SHA-256 hash of a string, optionally shortened to a number of hex characters.

NameTypeDescription
$stringstringThe string to hash.
$lengthintThe number of hex characters to keep (1 to 64, default 64).

Returns string The hash.

TextUrl

Read parts of a slash-separated URL path: the first segment, the segment after a given path, the remaining segments, and whether a path sits directly inside another.

FirstPart

TextUrl::FirstPart(string $urlPath): string

The first segment of a URL path.

NameTypeDescription
$urlPathstringThe URL path.

Returns string The first segment.

FirstPartAfter

TextUrl::FirstPartAfter(string $urlPath, string $afterPath): string

The first segment of a URL path that follows a given prefix path.

NameTypeDescription
$urlPathstringThe URL path.
$afterPathstringThe prefix path the URL path must start with.

Returns string The first segment after the prefix.

ImmediatelyInside

TextUrl::ImmediatelyInside(string $path, string $insideOfPath): bool

Whether a path is exactly one segment inside another path.

NameTypeDescription
$pathstringThe path to test.
$insideOfPathstringThe parent path.

Returns bool True when the path is one segment inside the parent.

NextParts

TextUrl::NextParts(string $urlPath): string

The URL path with its first segment removed.

NameTypeDescription
$urlPathstringThe URL path.

Returns string The remaining segments.