Primordyx Framework Documentation

Strings
in package

Class strings

A comprehensive utility class for working with strings in a multibyte-safe, Unicode-aware way. Provides tools for transformation, sanitization, validation, analysis, formatting, security, and fun.


🔤 TRANSFORMATION METHODS

  • toCamelCase()
  • toPascalCase() (via ucfirst(toCamelCase()))
  • toSnakeCase()
  • toKebabCase()
  • toTitleCase()
  • smartTitleCase()
  • slugify()
  • slugToTitle()
  • reverse()
  • reverseWords()
  • reverseLines()
  • truncate()
  • truncateMiddle()
  • limitWords()
  • wrap()
  • padLeft()
  • padRight()
  • center()
  • indent()
  • initials()
  • removePrefix()
  • removeSuffix()
  • replaceFirstPartOfString()
  • incrementString()

SANITIZATION / CLEANUP

  • clean()
  • collapseWhitespace()
  • stripPunctuation()
  • stripDiacritics()
  • stripHtmlButAllow()
  • strip()
  • normalizeWhitespace()
  • normalizeNewlinesToCrlf()
  • toAscii()
  • toAsciiSafe()
  • removeAccents()
  • stripNonPrintable()
  • sanitizeFilename()

VALIDATION & CHECKING

  • isAlpha()
  • isAlnum()
  • isLower()
  • isUpper()
  • hasMixedCase()
  • isLetters()
  • isLettersOrDigits()
  • isNumericString()
  • isBlank()
  • isJson()
  • isUrl()
  • isEmail()
  • isUuid()
  • isHex()
  • isValidBase64()
  • isAscii()
  • isPrintable()
  • isSentenceLike()
  • startsWith()
  • endsWith()
  • startsWithAny()
  • endsWithAny()
  • contains()
  • containsAny()
  • hasPrefixAny()
  • matchesPattern()
  • equalsIgnoreCase()
  • detectCaseStyle()

SECURITY & AUTH

  • constantTimeEquals()
  • signHmac()
  • verifyHmacSignature()
  • secureCompare() (alias of constantTimeEquals)
  • verifyTwilioSignature()

🔒 OBFUSCATION

  • obfuscateEmail()
  • obfuscatePhoneNumber()
  • obfuscateCreditCard()
  • obfuscatePostalCode()
  • obfuscatePassword()

📊 ANALYSIS & STATS

  • length()
  • byteLength()
  • wordCount()
  • sentenceCount()
  • charFrequency()
  • detectEncoding()

FUN & MISC

  • rot13()
  • shuffle()
  • randomString()
  • randomSlug()
  • isPalindrome()
  • extractBetween()
  • wordWrapHtmlSafe()
  • removeDuplicateWords()

CONVERSION & UTILITY

  • normalizeHex()
  • sanitizeHex()
  • guid()
  • uuid()
  • uuidV7()
  • toSlugId()

Table of Contents

Methods

between()  : string|null
Extracts the substring found between two delimiters within a string.
camelCase()  : string
Converts a string into camelCase format, intelligently handling various input styles.
center()  : string
Centers a string within a field of a given width using a specified padding character.
charFrequency()  : array<string|int, mixed>
Returns a frequency map of characters in the given string.
clean()  : string
Cleans up excess whitespace from a string.
collapseWhitespace()  : string
Collapses all sequences of whitespace (spaces, tabs, newlines) into a single space.
constantTimeEquals()  : bool
Compares two strings in constant time to prevent timing attacks.
contains()  : bool
Determines whether a given substring exists within a larger string.
containsAny()  : bool
Checks whether the input string contains any of the given substrings.
decrementString()  : string
Decrements a trailing numeric suffix on a string, optionally removing it if it reaches zero.
dedent()  : string
Removes the smallest common leading whitespace from all non-empty lines in a multiline string.
detectCaseStyle()  : string
Attempts to detect the casing style of a string.
detectEncoding()  : string|false
Attempts to detect the encoding of a string using mb_detect_encoding().
endsWith()  : bool
Checks whether a string ends with a given substring.
endsWithAny()  : bool
Checks whether the given string ends with any of the specified suffixes.
equalsIgnoreCase()  : bool
Compares two strings for equality, ignoring case differences.
excerpt()  : string
Extracts a contextual excerpt around the first occurrence of a query string.
formatCurrency()  : string
hasMixedCase()  : bool
Determines if a string contains both uppercase and lowercase characters.
hasPrefixAny()  : bool
Checks whether a string starts with any of the given prefixes.
incrementString()  : string
Appends or increments a trailing numeric suffix on a string, optionally zero-padded.
indent()  : string
Indents each line of a string by a given number of characters.
initials()  : string
Extracts the uppercase initials from a name or phrase.
isAlnum()  : bool
Checks whether a string contains only alphanumeric characters (A–Z, a–z, 0–9).
isAlpha()  : bool
Determines if a string contains only alphabetic characters (A–Z, a–z).
isAscii()  : bool
Checks whether a string contains only 7-bit ASCII characters.
isBlank()  : bool
Determines whether a string is blank (empty or contains only whitespace).
isEmail()  : bool
Validates whether a given string is a well-formed email address.
isHex()  : bool
Determines whether a string is a valid hexadecimal number.
isJson()  : bool
Determines whether a given string is valid JSON.
isLetters()  : bool
Determines if a string contains only Unicode letters (from any language).
isLettersOrDigits()  : bool
Determines if a string contains only Unicode letters or digits.
isLower()  : bool
Checks whether all characters in the string are lowercase.
isNumericString()  : bool
Determines if a string is a valid numeric value (int or float).
isPrintable()  : bool
Checks if a string contains only printable characters.
isSentenceLike()  : bool
Determines if a string resembles a sentence (starts with uppercase and ends with punctuation).
isStrictTitleCase()  : bool
Determines if a string is strictly title case: each word starts with a single uppercase letter, followed only by lowercase letters — excluding all-uppercase acronyms like 'NASA' or 'HTTP'.
isTitleCase()  : bool
Determines if a string is in title case (each word starts with an uppercase letter, followed by lowercase).
isUpper()  : bool
Checks whether all characters in the string are uppercase.
isUrl()  : bool
Validates whether a given string is a well-formed URL.
isUuid()  : bool
Validates whether a given string is a well-formed UUID (version 1 through 5).
isValidBase64()  : bool
Checks whether a string is a valid base64-encoded string.
kebabCase()  : string
Converts a string into kebab-case format.
length()  : int
Returns the number of characters in a string, using multibyte-safe logic.
limitChars()  : string
Truncates a string to a maximum number of characters, optionally avoiding mid-word breaks.
limitHtmlSafeChars()  : string
Truncates a string containing HTML to a maximum number of visible characters.
limitWords()  : string
Truncates a string after a specified number of words and appends an ellipsis (or other trailing marker).
loadCleanWordList()  : array<string|int, mixed>
Loads and filters a clean word list from a file like /usr/share/dict/words, with static caching.
mask()  : string
Masks all but the last few characters of a string using a specified mask character.
matchesPattern()  : bool
Determines whether a string matches a given regular expression pattern.
normalize_newlines_to_crlf()  : string
Normalizes all newline characters in a string to CRLF (`\r\n`) format.
normalizeHex()  : string
Normalizes a hexadecimal string by removing the optional "0x"/"0X" prefix and optionally converting to lowercase or uppercase.
normalizeWhitespace()  : string
Normalizes all whitespace in a string to single spaces and trims the result.
obfuscateCreditCard()  : string
Obfuscates a credit card number by masking all but the first and last 4 digits.
obfuscateEmail()  : string
Obfuscates an email address by masking the username portion with asterisks.
obfuscateMiddle()  : string
Obfuscates the middle portion of a string, preserving the beginning and end.
obfuscatePhoneNumber()  : string
Obfuscates a phone number by masking the middle digits with asterisks.
obfuscatePostalCode()  : string
Obfuscates a postal code by masking the middle digits with asterisks.
onlyAlpha()  : string
Removes all non-alphabetic characters from the input string.
onlyLetters()  : string
Removes all non-letter characters from the input string, including digits and symbols.
ordinal()  : string
Converts an integer into its ordinal string representation (e.g., 1 → "1st", 2 → "2nd").
outdent()  : string
Removes a fixed number of leading characters (indentation) from each line.
padLeft()  : string
Pads a string on the left side to a specified total length using a given padding character.
padRight()  : string
Pads a string on the right side to a specified total length using a given padding character.
randomSlugFromWordlist()  : string
Generates a human-friendly random slug using two words and a number.
randomString()  : string
Generates a cryptographically secure random string of a given length, optionally with a prefix.
removeAccents()  : string
Removes accents and diacritics from a UTF-8 string by converting to ASCII.
removeDuplicateWords()  : string
Removes consecutive duplicate words in a string.
removePrefix()  : string
Removes the given prefix from the start of a string, if present.
removeSuffix()  : string
Removes the given suffix from the end of a string, if present.
repeat()  : string
Repeats a string a specified number of times.
replaceFirstPartOfString()  : string
Replaces the beginning of a string with a new prefix of the same length.
reverse()  : string
Reverses a string safely with full multibyte (UTF-8) support.
reverseLines()  : string
Reverses the order of lines in a multiline string.
reverseWords()  : string
Reverses the order of words in a string while preserving the words themselves.
rot13()  : string
Applies the ROT13 cipher to a string.
safeHtml()  : string
Escapes special characters in a string for safe output in HTML.
sanitizeFilename()  : string
Sanitizes a string for use as a safe filename by replacing disallowed characters with underscores.
sanitizeHex()  : string|null
Validates and normalizes a hexadecimal string.
sentenceCount()  : int
Counts the number of sentences in a string.
shuffle()  : string
Randomly shuffles the characters in a multibyte string.
signHmac()  : string
Generates an HMAC signature for a payload using the given key and algorithm.
similarity()  : float
Calculates the percentage similarity between two strings.
slugify()  : string
Converts a string into a URL-friendly "slug" format.
slugToTitle()  : string
Converts a slug-formatted string into a human-readable title case string.
smartTitleCase()  : string
Converts a string to title case while preserving acronyms and lowercasing stop words.
snake_case()  : string
Converts a string into snake_case format.
startsWith()  : bool
Checks whether a string starts with a given substring.
startsWithAny()  : bool
Checks whether the given string starts with any of the specified prefixes.
strip()  : string
Removes all occurrences of the specified characters from a string.
stripDiacritics()  : string
Removes diacritical marks (accents) from characters while preserving the base letter.
stripHtmlButAllow()  : string
Strips all HTML tags from a string except those explicitly allowed.
stripNonPrintable()  : string
Removes all non-printable (control) characters from a string.
stripPunctuation()  : string
Removes all punctuation characters from a string, preserving letters, numbers, and whitespace.
titleCase()  : string
Converts a string to title case using multibyte-safe logic.
toAscii()  : string
Converts a UTF-8 string to an ASCII-only representation by transliterating accented and special characters.
toAsciiSafe()  : string
Converts a string to ASCII by transliterating or removing non-ASCII characters.
toCamelCase()  : string
Converts a string to camelCase.
toggleCase()  : string
Toggles the case of each character in a string.
toKebabCase()  : string
Converts a string to kebab-case.
toSlugId()  : string
Converts a string to a slug and appends an identifier, forming a slug-ID composite string.
toSnakeCase()  : string
Converts a string to snake_case.
toTitleCase()  : string
Converts a string to title case, capitalizing the first letter of each word.
truncate()  : string
Truncates a string to a specified length and appends an ellipsis (or other trailing marker).
ulid()  : string
Generates a ULID (Universally Unique Lexicographically Sortable Identifier).
ulidTimestamp()  : int
Extracts the timestamp (in milliseconds since Unix epoch) from a ULID string.
ulidTimestampToDateTime()  : DateTimeImmutable
Extracts the timestamp from a ULID and returns it as a DateTimeImmutable object.
uuid()  : string
Generates a RFC 4122–compliant UUID (version 4), with optional casing.
uuidv7()  : string
Generates a UUID version 7 (time-ordered + random) based on the draft UUIDv7 spec.
verifyHmacSignature()  : bool
Verifies an HMAC signature against a message and secret key using a constant-time comparison.
verifyTwilioSignature()  : bool
Verifies a Twilio webhook signature.
wordCount()  : int
Counts the number of words in a string, ignoring any HTML tags.
wordWrapHtmlSafe()  : string
Wraps long text inside HTML content without breaking tags.
wrap()  : string
Wraps a string with a given prefix and suffix.

Methods

between()

Extracts the substring found between two delimiters within a string.

public static between(string $str, string $start, string $end) : string|null

This method searches for the first occurrence of $start and $end within $str, and returns the substring between them. If either delimiter is not found in the proper order, the function returns null.

Parameters
$str : string

The full input string to search within.

$start : string

The starting delimiter. The result will begin immediately after this.

$end : string

The ending delimiter. The result will end just before this.

Tags
example
Strings::between('abc [target] def', '[', ']');     // 'target'
Strings::between('name: John, age: 42', 'name: ', ','); // 'John'
Strings::between('<<value>>', '<<', '>>');          // 'value'
edgecase

If $start is not found, or $end is not found after $start, the result is null. If $start and $end are the same and only appear once, or appear out of order, the result is null. If the string between delimiters is empty (e.g., abc[]def), an empty string is returned (''), not null.

note

This method only captures the first matching pair of delimiters. It does not support nested or repeated patterns. The search is case-sensitive and non-greedy.

Return values
string|null

Returns the substring between $start and $end, or null if the delimiters aren't found in order.

camelCase()

Converts a string into camelCase format, intelligently handling various input styles.

public static camelCase(string $str) : string

This method normalizes strings by converting delimiters (-, _, and spaces) into camelCase format. If the input string already appears to be in camelCase or PascalCase (and contains no delimiters), it will simply lowercase the first character to ensure camelCase conformity.

Parameters
$str : string

The input string to convert. May include delimiters or be already in PascalCase or camelCase.

Tags
example
Strings::camelCase('first_name');         // 'firstName'
Strings::camelCase('AlreadyCamelCase');   // 'alreadyCamelCase'
Strings::camelCase('user id');            // 'userId'
Strings::camelCase('super-duper-helper'); // 'superDuperHelper'
Strings::camelCase('JustWordsNoDelimiters'); // 'justWordsNoDelimiters'
edgecase

If the string contains no delimiters and already resembles camelCase or PascalCase, only the first character is lowercased. Empty strings will return as-is.

note

This function does not alter internal capitalization of words in preformatted camelCase input. It assumes you want to preserve existing word boundaries unless delimiters indicate otherwise.

Return values
string

The camelCased version of the string, with delimiters removed and word boundaries preserved.

center()

Centers a string within a field of a given width using a specified padding character.

public static center(string $str, int $width[, string $pad = ' ' ]) : string

This method calculates how much space is needed on each side of the string and pads it symmetrically (or near-symmetrically if the total padding is odd). Padding is added with the specified character, defaulting to a space.

Parameters
$str : string

The input string to center.

$width : int

The total width of the resulting string, including padding.

$pad : string = ' '

The character used for padding. Must be a non-empty string. Defaults to a space ' '.

Tags
example
Strings::center('hello', 11);         // '   hello   '
Strings::center('hello', 10, '-');    // '---hello--'
Strings::center('text', 4);           // 'text'
edgecase

If the padding character is an empty string, str_repeat() will emit a warning and return false. If the total padding is odd, the right side will receive one extra character.

note

This method uses mb_strlen() to ensure multibyte character safety when calculating width.

Return values
string

The centered string, padded to the specified width. If $width is less than or equal to the string's length, the original string is returned unchanged.

charFrequency()

Returns a frequency map of characters in the given string.

public static charFrequency(string $str) : array<string|int, mixed>

Keys are characters, values are occurrence counts. Multibyte-safe.

Parameters
$str : string

The input string.

Tags
example
Strings::charFrequency('hello') returns:
['h' => 1, 'e' => 1, 'l' => 2, 'o' => 1]
Return values
array<string|int, mixed>

Associative array of character => count.

clean()

Cleans up excess whitespace from a string.

public static clean(string $str) : string

This method collapses all sequences of whitespace (spaces, tabs, newlines) into a single space, and trims leading and trailing whitespace. Useful for sanitizing user input or preparing strings for display.

Parameters
$str : string

The input string to clean.

Tags
example
Strings::clean("  This   is  \n a   test\tstring. "); // 'This is a test string.'
Strings::clean("No extra   spaces");                 // 'No extra spaces'
edgecase

If the input string contains only whitespace, the result will be an empty string. If the input is already clean, it is returned unchanged.

note

This function does not remove or escape HTML tags, special characters, or punctuation— it deals with whitespace only.

Return values
string

A trimmed string with all internal whitespace normalized to single spaces.

collapseWhitespace()

Collapses all sequences of whitespace (spaces, tabs, newlines) into a single space.

public static collapseWhitespace(string $str) : string

Trims leading and trailing whitespace, then normalizes all internal whitespace to a single space character.

Parameters
$str : string

The input string.

Tags
example
Strings::collapseWhitespace(" Hello\t \n world!  ");  // 'Hello world!'
Return values
string

The string with normalized whitespace.

constantTimeEquals()

Compares two strings in constant time to prevent timing attacks.

public static constantTimeEquals(string $a, string $b) : bool

This method uses hash_equals() to safely compare secrets like API tokens, HMAC signatures, or passwords without leaking information through response timing.

Unlike a regular === comparison, this function ensures that the comparison takes the same amount of time regardless of how much of the input matches, which helps defend against timing-based side-channel attacks.

Parameters
$a : string

The expected (trusted) string.

$b : string

The actual (untrusted) string to compare.

Tags
example
Strings::constantTimeEquals('secret123', 'secret123');  // true
Strings::constantTimeEquals('secret123', 'secret124');  // false
note

This function should always be used for comparing sensitive values like tokens, signatures, or passwords — especially when accepting user input in authentication or verification flows.

Return values
bool

True if the strings are identical; false otherwise.

contains()

Determines whether a given substring exists within a larger string.

public static contains(string $haystack, string $needle) : bool

This method checks if $needle is found anywhere within $haystack. It uses strpos() under the hood, which is case-sensitive and returns false if the substring is not found.

Parameters
$haystack : string

The string to search within.

$needle : string

The substring to search for.

Tags
example
Strings::contains('hello world', 'world'); // true
Strings::contains('hello world', 'World'); // false (case-sensitive)
edgecase

If $needle is an empty string, this function will always return true, because strpos() treats an empty string as being found at the beginning of any string. Example: Strings::contains('anything', '') === true

note

This function is case-sensitive. For case-insensitive checks, use stripos() instead of strpos().

Return values
bool

Returns true if $needle exists within $haystack, otherwise false.

containsAny()

Checks whether the input string contains any of the given substrings.

public static containsAny(string $haystack, array<string|int, mixed> $needles[, bool $ignoreCase = false ]) : bool

Iterates through the array of needles and returns true as soon as one is found within the haystack. Optionally performs case-insensitive matching.

Parameters
$haystack : string

The string to search within.

$needles : array<string|int, mixed>

An array of substrings to look for.

$ignoreCase : bool = false

Whether to perform case-insensitive matching. Default is false.

Tags
example
Strings::containsAny('Hello World', ['world'], true);    // true
Strings::containsAny('ABC123', ['abc']);                 // false
Strings::containsAny('circle6mail', ['Mail'], true);     // true
Return values
bool

True if any needle is found in the haystack; false otherwise.

decrementString()

Decrements a trailing numeric suffix on a string, optionally removing it if it reaches zero.

public static decrementString(string $str[, string $separator = '_' ][, int|null $padWidth = null ][, bool $removeIfZero = false ][, bool $strictSuffixOnly = false ]) : string

If the string ends in a numeric suffix (e.g., "_002"), it will be decremented. Preserves separator and zero-padding unless the number reaches 0 and $removeIfZero is true. If no numeric suffix is found, the original string is returned unchanged.

Parameters
$str : string

The input string to modify.

$separator : string = '_'

The separator before the number. Default is "_".

$padWidth : int|null = null

If provided, output is zero-padded to this width. Otherwise, preserves original width.

$removeIfZero : bool = false

If true, removes the numeric suffix entirely when result reaches 0. Default is false.

$strictSuffixOnly : bool = false

If true, only decrements suffixes of the form "separator + digits". Default is false.

Tags
example
Strings::decrementString('file_007');                    // 'file_006'
Strings::decrementString('file_001', '_', 3, true);      // 'file'
Strings::decrementString('report-v2', '-', 3, true, true); // 'report-v2-000'
Strings::decrementString('file', '_');                   // 'file'
Return values
string

The decremented or cleaned string.

dedent()

Removes the smallest common leading whitespace from all non-empty lines in a multiline string.

public static dedent(string $str) : string

Useful for cleaning up heredoc strings, templates, or indented blocks without needing to know the exact indentation level.

Parameters
$str : string

The input string with consistent leading indentation.

Tags
example
Strings::dedent("    line 1\n    line 2\n    line 3");    // "line 1\nline 2\nline 3"
Strings::dedent("  foo\n    bar\n  baz");                 // "foo\n  bar\nbaz"
note

Blank lines are ignored when calculating minimum indentation. Works with spaces, tabs, or mixed whitespace — but doesn’t normalize them.

Return values
string

The dedented string.

detectCaseStyle()

Attempts to detect the casing style of a string.

public static detectCaseStyle(string $str) : string

Returns one of: 'camel', 'pascal', 'snake', 'kebab', 'title', 'upper', 'lower', or 'unknown'.

Parameters
$str : string

The string to analyze.

Tags
example
Strings::detectCaseStyle('helloWorld');     // 'camel'
Strings::detectCaseStyle('HelloWorld');     // 'pascal'
Strings::detectCaseStyle('hello_world');    // 'snake'
Strings::detectCaseStyle('hello-world');    // 'kebab'
Strings::detectCaseStyle('HELLO WORLD');    // 'upper'
Return values
string

The detected case style (or 'unknown').

detectEncoding()

Attempts to detect the encoding of a string using mb_detect_encoding().

public static detectEncoding(string $str) : string|false

Tries common encodings including UTF-8, ISO-8859-1, and Windows-1252.

Parameters
$str : string

The input string.

Tags
example
Strings::detectEncoding("hello");   // 'ASCII' or 'UTF-8'
Return values
string|false

The detected encoding (e.g., 'UTF-8') or false if undetectable.

endsWith()

Checks whether a string ends with a given substring.

public static endsWith(string $haystack, string $needle) : bool

This method determines if the $haystack string ends with the specified $needle. It compares the ending segment of $haystack (based on the length of $needle) to $needle itself.

Parameters
$haystack : string

The full string to evaluate.

$needle : string

The substring to check for at the end of $haystack.

Tags
example
Strings::endsWith('filename.txt', '.txt'); // true
Strings::endsWith('filename.txt', '.TXT'); // false (case-sensitive)
Strings::endsWith('hello', '');            // true (empty needle)
edgecase

An empty $needle will always return true, regardless of $haystack. This behavior might be unexpected in some cases. It stems from the logic that any string "ends with" an empty string.

note

This function is case-sensitive. For case-insensitive checks, consider converting both strings to a common case (strtolower() or mb_strtolower()) before comparison.

Return values
bool

Returns true if $haystack ends with $needle, or if $needle is an empty string; otherwise, false.

endsWithAny()

Checks whether the given string ends with any of the specified suffixes.

public static endsWithAny(string $haystack, array<string|int, mixed> $suffixes) : bool

Iterates through an array of possible suffixes and returns true as soon as one matches the end of the input string.

Parameters
$haystack : string

The string to check.

$suffixes : array<string|int, mixed>

An array of string suffixes to test against.

Tags
example
Strings::endsWithAny('report.csv', ['.csv', '.txt']);       // true
Strings::endsWithAny('hello-world.js', ['.php', '.html']);  // false
note

Comparison is case-sensitive. Use strtolower() on both haystack and suffixes if you need case-insensitive behavior.

Return values
bool

True if the string ends with any suffix in the array; false otherwise.

equalsIgnoreCase()

Compares two strings for equality, ignoring case differences.

public static equalsIgnoreCase(string $a, string $b) : bool

This method performs a case-insensitive comparison by converting both input strings to lowercase before comparing them using strict equality (===).

Parameters
$a : string

The first string to compare.

$b : string

The second string to compare.

Tags
example
Strings::equalsIgnoreCase('Hello', 'hello');     // true
Strings::equalsIgnoreCase('Test', 'TEST');       // true
Strings::equalsIgnoreCase('abc', 'abC');         // true
Strings::equalsIgnoreCase('abc', 'abcd');        // false
edgecase

Locale-sensitive characters (like ß, İ, or accented letters) may not behave as expected with strtolower() depending on the environment and encoding. For full Unicode case folding, use mb_strtolower() with an appropriate locale.

note

This function is ASCII-case-insensitive by default. It may not account for locale or multibyte edge cases unless mbstring functions are explicitly used.

Return values
bool

Returns true if the strings are equal when case is ignored; otherwise false.

excerpt()

Extracts a contextual excerpt around the first occurrence of a query string.

public static excerpt(string $str, string $query[, int $radius = 50 ]) : string

This method finds the first occurrence of $query (case-insensitive) in $str, then returns a snippet of text surrounding it — with up to $radius characters before and after the match — wrapped in ellipses.

Parameters
$str : string

The full text to search within.

$query : string

The substring to find within the text.

$radius : int = 50

The number of characters to include before and after the match. Defaults to 50.

Tags
example
Strings::excerpt('The quick brown fox jumps over the lazy dog', 'fox');
// '...quick brown fox jumps over the lazy...'
    *
Strings::excerpt('Nothing to see here', 'missing');
// ''
edgecase

If the query isn't found, the function returns an empty string. If the match is near the start or end of the string, the excerpt may be shorter than expected. If $query appears multiple times, only the first match is considered.

note

This method does not highlight the query term or ensure word boundaries — it’s intended for simple previews. Ellipses are always added at both ends, even if the excerpt begins at position 0 or ends at the string’s end.

Return values
string

A trimmed excerpt centered around the match, wrapped in ..., or an empty string if no match is found.

formatCurrency()

public static formatCurrency(float $amount) : string
Parameters
$amount : float
Return values
string

hasMixedCase()

Determines if a string contains both uppercase and lowercase characters.

public static hasMixedCase(string $str) : bool

Useful for detecting password strength, formatting errors, or inconsistent casing.

Parameters
$str : string

The string to evaluate.

Tags
example
Strings::hasMixedCase('Password123');  // true
Strings::hasMixedCase('password');     // false
Strings::hasMixedCase('PASSWORD');     // false
note

This function is multibyte-safe.

Return values
bool

True if the string contains at least one lowercase and one uppercase character; false otherwise.

hasPrefixAny()

Checks whether a string starts with any of the given prefixes.

public static hasPrefixAny(string $haystack, array<string|int, mixed> $prefixes) : bool

This method iterates over an array of possible prefixes and returns true as soon as one of them matches the beginning of the $haystack string. It uses the startsWith() method internally, so comparison is case-sensitive by default.

Parameters
$haystack : string

The string to evaluate.

$prefixes : array<string|int, mixed>

An array of prefix strings to test against the start of $haystack.

Tags
example
Strings::hasPrefixAny('foobar', ['foo', 'bar']);     // true
Strings::hasPrefixAny('hello world', ['hi', 'hey']); // false
Strings::hasPrefixAny('data.json', ['data.', 'meta.']); // true
edgecase

An empty $prefixes array will always return false since there's nothing to check against. If any prefix in the array is an empty string, it will always match (per startsWith() logic), causing the function to return true immediately.

note

This function performs a case-sensitive comparison. To make it case-insensitive, use a modified version of startsWith() with case normalization.

Return values
bool

Returns true if $haystack starts with at least one of the specified prefixes; otherwise false.

incrementString()

Appends or increments a trailing numeric suffix on a string, optionally zero-padded.

public static incrementString(string $str[, string $separator = '_' ][, int|null $padWidth = null ][, bool $strictSuffixOnly = false ]) : string

When a numeric suffix is present (e.g., "_7", "-099"), it is incremented. If no such suffix is found, "1" is appended using the separator and optional padding. When $strictSuffixOnly is true, suffix must be exactly separator followed by digits (e.g., "_123").

Parameters
$str : string

The input string to modify.

$separator : string = '_'

The separator to use before the number. Default is "_".

$padWidth : int|null = null

Optional zero-padding width (e.g., 3 → "007").

$strictSuffixOnly : bool = false

If true, only increments suffixes with exact separator + digits. Default is false.

Tags
example
Strings::incrementString('file');                         // 'file_1'
Strings::incrementString('report-v2', '-', 3);            // 'report-v003'
Strings::incrementString('report-v2', '-', 3, true);      // 'report-v2-001' (v2 not incremented)
Strings::incrementString('build-2023.12.01', '-', 3, true); // 'build-2023.12.01-001'
Return values
string

The incremented or newly suffixed string.

indent()

Indents each line of a string by a given number of characters.

public static indent(string $str[, int $spaces = 4 ][, string $char = ' ' ]) : string

Adds padding to the beginning of each line in a multiline string using the specified character. Useful for formatting logs, code, or nested structures.

Parameters
$str : string

The input string, possibly multiline.

$spaces : int = 4

The number of characters to indent each line. Default is 4.

$char : string = ' '

The character to use for indentation. Default is a space.

Tags
example
Strings::indent("line 1\nline 2");           // "    line 1\n    line 2"
Strings::indent("foo\nbar", 2, '-');         // "--foo\n--bar"
note

Applies to each line independently using ^ and multiline (/m) regex mode.

Return values
string

The indented string.

initials()

Extracts the uppercase initials from a name or phrase.

public static initials(string $str) : string

Useful for avatars, monograms, or shorthand labels.

Parameters
$str : string

The input string (e.g., full name).

Tags
example
Strings::initials('John Doe');        // 'JD'
Strings::initials('alice cooper');    // 'AC'
Return values
string

The concatenated initials in uppercase.

isAlnum()

Checks whether a string contains only alphanumeric characters (A–Z, a–z, 0–9).

public static isAlnum(string $str) : bool

Returns true if the string is non-empty and contains only ASCII letters and digits. No whitespace, punctuation, symbols, or Unicode characters are allowed.

Parameters
$str : string

The input string to check.

Tags
example
Strings::isAlnum('abc123');      // true
Strings::isAlnum('ABC');         // true
Strings::isAlnum('123');         // true
Strings::isAlnum('abc 123');     // false (contains space)
Strings::isAlnum('naïve');       // false (accented i)
note

This is an ASCII-only check. For Unicode support (e.g., non-English letters and digits), use a Unicode-aware alternative like isLettersOrDigits().

Return values
bool

True if the string contains only alphanumeric ASCII characters; false otherwise.

isAlpha()

Determines if a string contains only alphabetic characters (A–Z, a–z).

public static isAlpha(string $str) : bool

Returns true if the string is non-empty and contains only English letters. No digits, spaces, symbols, or non-ASCII letters are allowed.

Parameters
$str : string

The input string to test.

Tags
example
Strings::isAlpha('abc');        // true
Strings::isAlpha('ABCdef');     // true
Strings::isAlpha('abc123');     // false
Strings::isAlpha('café');       // false (accented é is not A–Z)
note

This is ASCII-only. For Unicode letters (e.g., accents, other scripts), use Strings::onlyLetters() with a Unicode-aware regex like \p{L}.

Return values
bool

True if the string contains only A–Z or a–z; false otherwise.

isAscii()

Checks whether a string contains only 7-bit ASCII characters.

public static isAscii(string $str) : bool

Returns true if the string contains only standard printable ASCII characters (code points 0–127), including control characters, spaces, and basic punctuation. Any multibyte or extended characters will cause this to return false.

Parameters
$str : string

The input string to evaluate.

Tags
example
Strings::isAscii('Hello123');         // true
Strings::isAscii('Café');             // false (é is non-ASCII)
Strings::isAscii("Line\nBreak");      // true (newline is ASCII)
note

Uses mb_check_encoding() for reliable detection. If you want to detect only printable ASCII, use Strings::isPrintable() in combination with this method.

Return values
bool

True if the string is valid 7-bit ASCII; false otherwise.

isBlank()

Determines whether a string is blank (empty or contains only whitespace).

public static isBlank(string $str) : bool

This method trims the string and checks if anything remains. Returns true for strings like "", " ", "\n", or "\t".

Parameters
$str : string

The input string to check.

Tags
example
Strings::isBlank("");           // true
Strings::isBlank("    ");       // true
Strings::isBlank("\n\t\r");     // true
Strings::isBlank("hello");      // false
Return values
bool

True if the string is blank or only whitespace; false otherwise.

isEmail()

Validates whether a given string is a well-formed email address.

public static isEmail(string $str) : bool

This method uses filter_var() with the FILTER_VALIDATE_EMAIL flag to check if the input string adheres to the general format of an email address (e.g., user@example.com).

Parameters
$str : string

The input string to validate as an email address.

Tags
example
Strings::isEmail('user@example.com');    // true
Strings::isEmail('bad-email@');          // false
Strings::isEmail('user@localhost');      // false (fails under strict RFC rules)
Strings::isEmail('user.name+tag@domain.com'); // true
edgecase

Some technically valid but rare email formats may fail (e.g., Unicode domains, quoted local-parts), depending on PHP version and filter_var() implementation.

note

This validation checks basic syntax only. It does not verify whether the domain exists or whether the email address is deliverable.

Return values
bool

Returns true if the input is a valid email address, otherwise false.

isHex()

Determines whether a string is a valid hexadecimal number.

public static isHex(string $str[, bool $allowPrefix = false ]) : bool

Validates that the string contains only hexadecimal characters (0–9, a–f, A–F). Optionally allows a "0x" or "0X" prefix if $allowPrefix is true.

Parameters
$str : string

The string to evaluate.

$allowPrefix : bool = false

Whether to allow an optional '0x' or '0X' prefix. Default is false.

Tags
example
Strings::isHex('deadBEEF');           // true
Strings::isHex('0x123abc');           // false
Strings::isHex('0x123abc', true);     // true
Strings::isHex('g123');               // false
Strings::isHex('');                   // false
Return values
bool

True if the string is a valid hex value; false otherwise.

isJson()

Determines whether a given string is valid JSON.

public static isJson(string $str) : bool

This method attempts to decode the string using json_decode() and checks whether any errors occurred. It returns true if the string is valid JSON, even if the decoded result is null, false, or another non-object value.

Parameters
$str : string

The string to test for JSON validity.

Tags
example
Strings::isJson('{"key":"value"}');      // true
Strings::isJson('[1, 2, 3]');             // true
Strings::isJson('"Just a string"');      // true
Strings::isJson('null');                 // true
Strings::isJson('not json');             // false
edgecase

This function will return true for valid JSON values like "true", "42", or "null", which may not be what some callers expect if they're only checking for objects or arrays.

note

This does not check the type of JSON structure — only that the input is syntactically valid. To ensure the decoded result is an array or object, you must additionally inspect the result of json_decode().

Return values
bool

Returns true if the string is valid JSON syntax; otherwise false.

isLetters()

Determines if a string contains only Unicode letters (from any language).

public static isLetters(string $str) : bool

Uses the Unicode character class \p{L} to match all letter types, including accented Latin letters, Cyrillic, Greek, and others. Does not allow digits, punctuation, or symbols.

Parameters
$str : string

The input string to evaluate.

Tags
example
Strings::isLetters('abc');           // true
Strings::isLetters('CrèmeBrûlée');   // true
Strings::isLetters('Москва');        // true
Strings::isLetters('hello123');      // false
Strings::isLetters('naïve!');        // false (contains punctuation)
note

Blank strings will return false. Matching is Unicode-aware and multibyte-safe.

Return values
bool

True if the string contains only letters; false otherwise.

isLettersOrDigits()

Determines if a string contains only Unicode letters or digits.

public static isLettersOrDigits(string $str) : bool

Uses the Unicode character classes \p{L} (letters) and \p{N} (numbers) to validate multilingual, multibyte-safe alphanumeric content. Accepts non-English characters and digits from any script.

Parameters
$str : string

The string to evaluate.

Tags
example
Strings::isLettersOrDigits('abc123');      // true
Strings::isLettersOrDigits('Crème123');    // true
Strings::isLettersOrDigits('Москва2024');  // true
Strings::isLettersOrDigits('abc!123');     // false (contains punctuation)
note

This method is multibyte-aware and supports full Unicode. An empty string will return false.

Return values
bool

True if the string contains only letters or digits (no punctuation or symbols); false otherwise.

isLower()

Checks whether all characters in the string are lowercase.

public static isLower(string $str) : bool

Uses mb_strtolower() to compare against the original input. Returns true only if the input is non-empty and already entirely lowercase (including multibyte characters).

Parameters
$str : string

The input string to evaluate.

Tags
example
Strings::isLower('hello');         // true
Strings::isLower('HELLO');         // false
Strings::isLower('Crème');         // false (C is uppercase)
Strings::isLower('straße');        // true (ß is lowercase)
note

This method is multibyte-safe. Returns false for empty strings.

Return values
bool

True if all characters are lowercase; false otherwise.

isNumericString()

Determines if a string is a valid numeric value (int or float).

public static isNumericString(string $str) : bool

Accepts optional signs, decimal points, and scientific notation (e.g., '1e6').

Parameters
$str : string

The input string to test.

Tags
example
Strings::isNumericString('123');      // true
Strings::isNumericString('-12.5e3');  // true
Strings::isNumericString('123abc');   // false
Return values
bool

True if the string is numeric; false otherwise.

isPrintable()

Checks if a string contains only printable characters.

public static isPrintable(string $str) : bool

Uses the Unicode \P{C} property to reject control characters (e.g., newlines, null bytes, etc.). Returns true if the string is non-empty and contains no control or non-character code points.

Parameters
$str : string

The input string to evaluate.

Tags
example
Strings::isPrintable('hello');              // true
Strings::isPrintable("hello\nworld");       // false
Strings::isPrintable('🚀 Launch!');          // true
Strings::isPrintable("abc\x00def");         // false (contains null byte)
note

This is Unicode-aware and multibyte-safe. It does not filter whitespace like spaces or tabs, only non-printable control characters (General Category: C* in Unicode).

Return values
bool

True if all characters are printable; false otherwise.

isSentenceLike()

Determines if a string resembles a sentence (starts with uppercase and ends with punctuation).

public static isSentenceLike(string $str) : bool

Useful for validating user input, UI messages, or natural language checks.

Parameters
$str : string

The string to evaluate.

Tags
example
Strings::isSentenceLike('Hello world.');   // true
Strings::isSentenceLike('hello world');    // false
Return values
bool

True if the string looks like a sentence; false otherwise.

isStrictTitleCase()

Determines if a string is strictly title case: each word starts with a single uppercase letter, followed only by lowercase letters — excluding all-uppercase acronyms like 'NASA' or 'HTTP'.

public static isStrictTitleCase(string $str) : bool
Parameters
$str : string

The input string to evaluate.

Tags
example
Strings::isStrictTitleCase('The Quick Brown Fox');   // true
Strings::isStrictTitleCase('NASA Launch Site');      // false
Strings::isStrictTitleCase('The NASA Space Center'); // false
note

This method is multibyte-safe and Unicode-aware. Words are split on whitespace.

Return values
bool

True if the string is strictly title-cased; false otherwise.

isTitleCase()

Determines if a string is in title case (each word starts with an uppercase letter, followed by lowercase).

public static isTitleCase(string $str) : bool

Checks that all words begin with \p{Lu} (uppercase letter) followed by zero or more \p{Ll} (lowercase letters).

Parameters
$str : string

The string to check.

Tags
example
Strings::isTitleCase('The Quick Brown Fox');    // true
Strings::isTitleCase('the Quick Brown Fox');    // false
Strings::isTitleCase('Das Ist Gut');            // true
note

This method is Unicode-aware and multibyte-safe. Words are split on whitespace.

Return values
bool

True if all words are title-cased; false otherwise.

isUpper()

Checks whether all characters in the string are uppercase.

public static isUpper(string $str) : bool

Uses mb_strtoupper() to compare against the original input. Returns true only if the input is non-empty and already entirely uppercase (including multibyte characters).

Parameters
$str : string

The input string to evaluate.

Tags
example
Strings::isUpper('HELLO');         // true
Strings::isUpper('hello');         // false
Strings::isUpper('CRÈME');         // true
Strings::isUpper('München');       // false (ü is lowercase)
note

This method is multibyte-safe and works with accented/Unicode characters. Returns false for empty strings.

Return values
bool

True if all characters are uppercase; false otherwise.

isUrl()

Validates whether a given string is a well-formed URL.

public static isUrl(string $str) : bool

This method uses filter_var() with the FILTER_VALIDATE_URL flag to determine if the input string conforms to standard URL formatting (e.g., includes a valid scheme and host).

Parameters
$str : string

The input string to validate as a URL.

Tags
example
Strings::isUrl('https://example.com');         // true
Strings::isUrl('http://localhost:8000/test');  // true
Strings::isUrl('ftp://example.com/resource');  // true
Strings::isUrl('www.example.com');             // false (missing scheme)
edgecase

URLs without a scheme (like www.example.com) will fail, even though browsers accept them. URLs with uncommon schemes or IP addresses may be flagged as invalid depending on the environment.

note

This method only checks the syntactic validity of the URL — it does not confirm that the domain exists or that the URL is reachable.

Return values
bool

Returns true if the input is a valid URL, otherwise false.

isUuid()

Validates whether a given string is a well-formed UUID (version 1 through 5).

public static isUuid(string $str) : bool

This method uses a regular expression to check that the input matches the standard UUID format: xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx, where:

  • M is a version digit (1–5)
  • N is a variant digit (8, 9, a, or b)
Parameters
$str : string

The string to validate as a UUID.

Tags
example
Strings::isUuid('550e8400-e29b-41d4-a716-446655440000'); // true
Strings::isUuid('not-a-uuid');                           // false
Strings::isUuid('123e4567-e89b-12d3-a456-426614174000'); // true
edgecase

This validator only accepts UUIDs with hyphens and lowercase/uppercase hex characters. It will reject nil UUIDs (00000000-0000-0000-0000-000000000000) if version or variant bits don't conform.

note

This checks only the format and version compliance — it does not guarantee the UUID was generated correctly or is unique. Adjust the regex if you need to accept other UUID variants (e.g., version 0 or nil UUIDs).

Return values
bool

Returns true if the string is a valid version 1–5 UUID, otherwise false.

isValidBase64()

Checks whether a string is a valid base64-encoded string.

public static isValidBase64(string $str) : bool

Validates character set and length. Optionally accepts padding.

Parameters
$str : string

The input string to check.

Tags
example
Strings::isValidBase64('aGVsbG8=');      // true
Strings::isValidBase64('hello');         // false
Return values
bool

True if the string is valid base64; false otherwise.

kebabCase()

Converts a string into kebab-case format.

public static kebabCase(string $str) : string

This method replaces all sequences of non-letter and non-number characters with hyphens, trims leading and trailing hyphens, and lowercases the result. It's ideal for creating SEO-friendly URL slugs or CSS class names from arbitrary input.

Parameters
$str : string

The input string to convert. May contain spaces, punctuation, or symbols.

Tags
example
Strings::kebabCase('Hello World!');           // 'hello-world'
Strings::kebabCase('already-kebab-case');     // 'already-kebab-case'
Strings::kebabCase('Multiple---delimiters');  // 'multiple-delimiters'
Strings::kebabCase('Ünicode & Symbols ™️');   // 'ünicode-symbols'
edgecase

If the input contains only symbols or whitespace, the result may be an empty string. Consecutive non-word characters are collapsed into a single hyphen.

note

This function is Unicode-aware via \p{L} (letters) and \p{N} (numbers), and uses the u modifier for proper multibyte string handling.

Return values
string

A kebab-cased version of the string, with lowercase letters, numbers, and hyphens only.

length()

Returns the number of characters in a string, using multibyte-safe logic.

public static length(string $str) : int

This method uses mb_strlen() to count characters rather than bytes, making it safe for UTF-8 and other multibyte encodings. It's suitable for accurately measuring the visible or logical length of a string containing Unicode characters.

Parameters
$str : string

The input string to measure.

Tags
example
Strings::length('Hello');          // 5
Strings::length('💡 Idea!');       // 7
Strings::length('naïve');          // 5
edgecase

If the input string is empty, the result will be 0.

note

This method depends on the mbstring extension. If it's not available, mb_strlen() may cause a fatal error or return incorrect results.

Return values
int

The number of characters in the string.

limitChars()

Truncates a string to a maximum number of characters, optionally avoiding mid-word breaks.

public static limitChars(string $str, int $maxChars[, string $ellipsis = '…' ][, bool $preserveWords = false ]) : string

If the string is shorter than or equal to the limit, it is returned as-is. If truncated, the ellipsis is appended and included in the total length.

Parameters
$str : string

The input string.

$maxChars : int

Maximum total characters, including ellipsis.

$ellipsis : string = '…'

String to append after truncation. Default is '…'.

$preserveWords : bool = false

If true, avoid breaking words in the middle.

Tags
example
Strings::limitChars("Hello world, how are you?", 10);                  // "Hello w…"
Strings::limitChars("Hello world, how are you?", 10, '…', true);       // "Hello…"
Strings::limitChars("Short", 10);                                      // "Short"
Return values
string

The truncated string, with ellipsis if applicable.

limitHtmlSafeChars()

Truncates a string containing HTML to a maximum number of visible characters.

public static limitHtmlSafeChars(string $html, int $maxChars[, string $ellipsis = '…' ][, bool $preserveWords = false ]) : string

This method:

  • Strips tags for counting visible characters
  • Preserves whole HTML tag structure (no broken tags)
  • Optionally avoids breaking mid-word
  • Appends an ellipsis or custom suffix if truncated
Parameters
$html : string

The HTML string.

$maxChars : int

Max visible characters, including ellipsis.

$ellipsis : string = '…'

What to append if truncated. Default is '…'.

$preserveWords : bool = false

Whether to avoid cutting mid-word.

Tags
example
Strings::limitHtmlSafeChars('<b>Hello</b> world!', 8); // "<b>Hello</b> w…"
Return values
string

Truncated HTML-safe string.

limitWords()

Truncates a string after a specified number of words and appends an ellipsis (or other trailing marker).

public static limitWords(string $str, int $maxWords[, string $ellipsis = '…' ]) : string

This method splits the input string into words using whitespace, and returns the first $maxWords joined by spaces. If the input has fewer than or equal to $maxWords, it is returned unchanged.

Parameters
$str : string

The input string to process.

$maxWords : int

The maximum number of words to retain.

$ellipsis : string = '…'

The string to append if truncation occurs. Defaults to a Unicode ellipsis ().

Tags
example
Strings::limitWords('The quick brown fox jumps over the lazy dog', 4);      // 'The quick brown fox…'
Strings::limitWords('Short sentence.', 5);                                   // 'Short sentence.'
Strings::limitWords('One two three four five', 3, '...');                    // 'One two three...'
edgecase

If $maxWords is zero or negative, the result will be just the ellipsis. If the input string is empty or contains only whitespace, it returns an empty string.

note

Words are determined using preg_split('/\s+/'), so any sequence of whitespace is considered a separator. This method does not account for punctuation or HTML tags when splitting words.

Return values
string

The truncated string if word count exceeds the limit, or the original string otherwise.

loadCleanWordList()

Loads and filters a clean word list from a file like /usr/share/dict/words, with static caching.

public static loadCleanWordList([string $path = '/usr/share/dict/words' ][, int $minLen = 3 ][, int $maxLen = 12 ]) : array<string|int, mixed>

Only includes lowercase ASCII words without punctuation, between $minLen and $maxLen characters.

Parameters
$path : string = '/usr/share/dict/words'

Path to the wordlist file. Defaults to /usr/share/dict/words.

$minLen : int = 3

Minimum word length to include. Defaults to 3.

$maxLen : int = 12

Maximum word length to include. Defaults to 12.

Tags
throws
RuntimeException

If the file is missing or unreadable.

Return values
array<string|int, mixed>

An array of lowercase, clean words.

mask()

Masks all but the last few characters of a string using a specified mask character.

public static mask(string $str[, int $visible = 4 ][, string $maskChar = '*' ]) : string

This method replaces all characters in the string with a masking character (e.g., *), except for the last $visible characters. It's commonly used for partially hiding sensitive data like credit card numbers or email usernames.

Parameters
$str : string

The input string to mask.

$visible : int = 4

The number of characters to leave visible at the end of the string. Defaults to 4.

$maskChar : string = '*'

The character to use for masking. Defaults to '*'.

Tags
example
Strings::mask('123456789', 4);       // '*****6789'
Strings::mask('secret', 2, '#');     // '####et'
Strings::mask('short', 10);          // '*****' (input too short to preserve visibility)
edgecase

If $visible is greater than or equal to the length of $str, the entire string will be masked. If $maskChar is an empty string, str_repeat() will emit a warning and return false.

note

This method uses mb_strlen() and mb_substr() to ensure multibyte safety. Always validate $maskChar to avoid unexpected behavior when empty.

Return values
string

The masked string, with all but the last $visible characters replaced by $maskChar.

matchesPattern()

Determines whether a string matches a given regular expression pattern.

public static matchesPattern(string $str, string $pattern) : bool

This method uses preg_match() to test whether the input string matches the specified pattern. It returns true if the pattern matches at least once, and false otherwise.

Parameters
$str : string

The input string to evaluate.

$pattern : string

A valid regular expression pattern, including delimiters (e.g., '/^abc/i').

Tags
example
Strings::matchesPattern('hello123', '/\d+/');     // true
Strings::matchesPattern('abc', '/^a/');           // true
Strings::matchesPattern('test', '/\d+/');         // false
Strings::matchesPattern('Test', '/test/i');       // true (case-insensitive)
edgecase

If the pattern is invalid (e.g., bad syntax or delimiters), preg_match() will return false and may trigger a warning or error depending on error reporting settings.

note

Always validate or escape user-supplied patterns before using them, to avoid security issues or unintended behavior. Patterns must include valid delimiters and optional flags.

Return values
bool

Returns true if the pattern matches the string; otherwise false.

normalize_newlines_to_crlf()

Normalizes all newline characters in a string to CRLF (`\r\n`) format.

public static normalize_newlines_to_crlf(string $input) : string

This method first converts all carriage returns (\r) to line feeds (\n) to avoid producing duplicate carriage returns when normalizing. It then replaces all line feeds with CRLF sequences. This is useful for ensuring consistent line endings for systems (like Windows or email protocols) that expect CRLF format.

Parameters
$input : string

The input string that may contain mixed or inconsistent newline characters.

Tags
example
Strings::normalize_newlines_to_crlf("Line 1\rLine 2\nLine 3\r\n");
// "Line 1\r\nLine 2\r\nLine 3\r\n"
edgecase

Any existing \r\n sequences will be preserved correctly after transformation. Lone \r or \n sequences will be safely converted into consistent \r\n.

note

This method is useful when preparing files for Windows environments, email headers, or protocols where CRLF is the required newline format.

Return values
string

The string with all newlines normalized to \r\n.

normalizeHex()

Normalizes a hexadecimal string by removing the optional "0x"/"0X" prefix and optionally converting to lowercase or uppercase.

public static normalizeHex(string $hex[, bool $toUpper = false ]) : string
Parameters
$hex : string

The input hex string (with or without prefix).

$toUpper : bool = false

Whether to convert the result to uppercase. Default is false (lowercase).

Tags
example
Strings::normalizeHex('0xDEADBEEF');    // 'deadbeef'
Strings::normalizeHex('abc123');        // 'abc123'
Strings::normalizeHex('0xABC123', true); // 'ABC123'
note

Does not validate the input. Use Strings::isHex() first if needed.

Return values
string

The normalized hex string with no prefix and consistent casing.

normalizeWhitespace()

Normalizes all whitespace in a string to single spaces and trims the result.

public static normalizeWhitespace(string $str) : string

This method collapses all consecutive whitespace characters (spaces, tabs, newlines, etc.) into a single space using a Unicode-aware regular expression. Leading and trailing whitespace are also removed with trim().

Parameters
$str : string

The input string to normalize.

Tags
example
Strings::normalizeWhitespace("  This\t is\n\nmessy   text. ");  // 'This is messy text.'
Strings::normalizeWhitespace("Line 1\nLine 2\r\nLine 3");       // 'Line 1 Line 2 Line 3'
edgecase

If the input string contains only whitespace, the result will be an empty string. Unicode whitespace (e.g., non-breaking space \u00A0) is treated as whitespace due to the \s pattern and u modifier.

note

The regular expression uses the u (Unicode) modifier for multibyte safety. This function is ideal for sanitizing user input or normalizing content before display or storage.

Return values
string

A clean string with all internal whitespace reduced to single spaces, and no leading or trailing whitespace.

obfuscateCreditCard()

Obfuscates a credit card number by masking all but the first and last 4 digits.

public static obfuscateCreditCard(string $creditCard[, bool $grouped = false ][, string $maskChar = '*' ]) : string

Non-digit characters (spaces, dashes, etc.) are stripped before processing. Optionally formats the result in grouped blocks of 4 digits/asterisks for readability.

Parameters
$creditCard : string

The raw credit card number input.

$grouped : bool = false

Whether to format the result with grouped blocks (e.g., 4111 **** **** 1111). Defaults to false.

$maskChar : string = '*'
Tags
example
Strings::obfuscateCreditCard('4111 1111 1111 1111');          // '4111********1111'
Strings::obfuscateCreditCard('4111-1111-1111-1111', true);    // '4111 **** **** 1111'
note

The method does not perform any credit card validation (Luhn, issuer, etc.). Input should contain at least 8 digits to produce a meaningful result.

Return values
string

The obfuscated credit card string.

obfuscateEmail()

Obfuscates an email address by masking the username portion with asterisks.

public static obfuscateEmail(string $email) : string

Reveals only the first and last character of the local part (before the @), and preserves the domain. Useful for safely displaying or logging emails without exposing the full address.

Parameters
$email : string

The full email address to obfuscate.

Tags
example
Strings::obfuscateEmail('john.doe@example.com');    // 'j******e@example.com'
Strings::obfuscateEmail('a@b.com');                 // 'a@b.com'
Strings::obfuscateEmail('xy@domain.com');           // 'x*y@domain.com'
note

This method assumes a valid email with a single '@'. Invalid input may cause errors or incorrect formatting.

Return values
string

The obfuscated email, e.g., j****e@example.com

obfuscateMiddle()

Obfuscates the middle portion of a string, preserving the beginning and end.

public static obfuscateMiddle(string $input[, int $visibleStart = 3 ][, int $visibleEnd = 4 ][, string $maskChar = '*' ]) : string
Parameters
$input : string

The string to obfuscate (API key, token, etc.).

$visibleStart : int = 3

Number of visible characters at the beginning.

$visibleEnd : int = 4

Number of visible characters at the end.

$maskChar : string = '*'

Masking character to use. Defaults to '*'.

Tags
example
Strings::obfuscateMiddle('sk_test_abc1234567890xyz', 7, 4);  // 'sk_test****************xyz'
Strings::obfuscateMiddle('abc123', 2, 2);                    // 'ab**23'
Return values
string

The obfuscated string.

obfuscatePhoneNumber()

Obfuscates a phone number by masking the middle digits with asterisks.

public static obfuscatePhoneNumber(string $phoneNumber) : string

Keeps the first 3 digits and the last 4 digits visible, replacing the middle portion with asterisks. Non-digit characters are stripped before processing.

Parameters
$phoneNumber : string

The input phone number (may contain spaces, dashes, etc.).

Tags
example
Strings::obfuscatePhoneNumber('123-456-7890');    // '123***7890'
Strings::obfuscatePhoneNumber('(800) 555-1212');  // '800*****1212'
note

This assumes U.S.-style phone numbers with at least 7 digits. If fewer than 7 digits, the result may expose more or all digits.

Return values
string

The obfuscated phone number, e.g., 123****7890

obfuscatePostalCode()

Obfuscates a postal code by masking the middle digits with asterisks.

public static obfuscatePostalCode(string $postalCode) : string

Keeps the first 3 digits and the last 4 digits (if present), masking anything in between. Non-digit characters are stripped before processing.

Parameters
$postalCode : string

The postal code (ZIP, ZIP+4, etc.) to obfuscate.

Tags
example
Strings::obfuscatePostalCode('78701');           // '787*1'
Strings::obfuscatePostalCode('78701-0423');      // '787****0423'
note

This assumes U.S.-style ZIP or ZIP+4 formats. Input with fewer than 5 digits may not be obfuscated meaningfully. If the input has fewer than 4 trailing digits, the ending portion will be as long as possible.

Return values
string

The obfuscated postal code, e.g., 787****0423

onlyAlpha()

Removes all non-alphabetic characters from the input string.

public static onlyAlpha(string $str) : string

Retains only uppercase and lowercase English letters (A–Z, a–z). All digits, punctuation, symbols, and whitespace are stripped.

Parameters
$str : string

The input string to sanitize.

Tags
example
Strings::onlyAlpha('abc123!@#');      // 'abc'
Strings::onlyAlpha('Circle-6 Mail');  // 'CircleMail'
Strings::onlyAlpha('42');             // ''
note

This does not support accented or Unicode letters. Use a Unicode-aware version (e.g., \p{L}) if working with non-ASCII alphabets.

Return values
string

The string containing only alphabetic characters.

onlyLetters()

Removes all non-letter characters from the input string, including digits and symbols.

public static onlyLetters(string $str) : string

This version is Unicode-aware and preserves letters from all languages and alphabets (e.g., Latin, Cyrillic, Greek, accented characters, etc.).

Parameters
$str : string

The input string to filter.

Tags
example
Strings::onlyLetters('abc123');         // 'abc'
Strings::onlyLetters('Crème brûlée!');  // 'Crèmebrûlée'
Strings::onlyLetters('Москва 2024');    // 'Москва'
note

Uses Unicode \p{L} character class to match any kind of letter. Requires the u (UTF-8) modifier to work properly with multibyte characters.

Return values
string

The string containing only Unicode letter characters.

ordinal()

Converts an integer into its ordinal string representation (e.g., 1 → "1st", 2 → "2nd").

public static ordinal(int $number) : string

This method appends the appropriate ordinal suffix (st, nd, rd, th) to a number, handling special exceptions for 11, 12, and 13, which always use th regardless of the last digit.

Parameters
$number : int

The integer to convert.

Tags
example
Strings::ordinal(1);   // '1st'
Strings::ordinal(2);   // '2nd'
Strings::ordinal(3);   // '3rd'
Strings::ordinal(4);   // '4th'
Strings::ordinal(11);  // '11th'
Strings::ordinal(22);  // '22nd'
Strings::ordinal(113); // '113th'
edgecase

Numbers ending in 11, 12, or 13 always return 'th' due to English ordinal rules, even though they end in 1, 2, or 3 (e.g., 111 → '111th', not '111st').

note

This method assumes input is a non-negative integer. Negative numbers will still return a valid string with the correct suffix, but the format (e.g., -1st) may not be meaningful in all contexts.

Return values
string

The ordinal representation of the number (e.g., "21st", "42nd", "113th").

outdent()

Removes a fixed number of leading characters (indentation) from each line.

public static outdent(string $str[, int $count = 4 ][, string $char = ' ' ]) : string

Useful for reversing indent(), reformatting text, or cleaning up deeply nested blocks. Only removes characters if they match the given character and are present at the start of the line.

Parameters
$str : string

The multiline string to outdent.

$count : int = 4

Number of leading characters to remove per line. Default is 4.

$char : string = ' '

The character to remove. Default is space.

Tags
example
Strings::outdent("    line 1\n    line 2");     // "line 1\nline 2"
Strings::outdent("--foo\n--bar", 2, '-');       // "foo\nbar"
note

This only removes characters if they match the specified character exactly. Mixed indentation (e.g. tabs + spaces) must be normalized first.

Return values
string

The de-indented string.

padLeft()

Pads a string on the left side to a specified total length using a given padding character.

public static padLeft(string $str, int $length[, string $char = ' ' ]) : string

This method uses str_pad() with STR_PAD_LEFT to add the specified character to the beginning of the string until the desired length is reached. If the original string is already at or longer than the target length, it is returned unchanged.

Parameters
$str : string

The input string to pad.

$length : int

The total length of the resulting string after padding.

$char : string = ' '

The character to pad with. Must be a non-empty string. Defaults to a space ' '.

Tags
example
Strings::padLeft('42', 5);               // '   42'
Strings::padLeft('abc', 6, '0');         // '000abc'
Strings::padLeft('already long', 5);     // 'already long'
edgecase

If $char is an empty string, str_pad() will emit a warning and return false. Always ensure $char is a non-empty string.

note

Padding is repeated as needed to fill the gap. If the padding string is longer than one character, it will be truncated if it doesn’t divide evenly into the padding length.

Return values
string

The left-padded string, or the original string if it is already equal to or longer than $length.

padRight()

Pads a string on the right side to a specified total length using a given padding character.

public static padRight(string $str, int $length[, string $char = ' ' ]) : string

This method uses str_pad() with STR_PAD_RIGHT to add the specified character to the end of the string until the desired length is reached. If the original string is already at or longer than the target length, it is returned unchanged.

Parameters
$str : string

The input string to pad.

$length : int

The total desired length of the resulting string after padding.

$char : string = ' '

The character to pad with. Must be a non-empty string. Defaults to a space ' '.

Tags
example
Strings::padRight('42', 5);               // '42   '
Strings::padRight('abc', 6, '.');         // 'abc...'
Strings::padRight('already long', 5);     // 'already long'
edgecase

If $char is an empty string, str_pad() will emit a warning and return false. Be sure to use a non-empty string for padding.

note

If the padding string is more than one character, it will repeat as needed and be truncated to fit the exact length.

Return values
string

The right-padded string, or the original string if it is already equal to or longer than $length.

randomSlugFromWordlist()

Generates a human-friendly random slug using two words and a number.

public static randomSlugFromWordlist([array<string|int, mixed>|null $wordlist = null ][, int $numberRange = 100 ][, string $separator = '-' ][, string $prefix = '' ][, string $suffix = '' ]) : string

Useful for URLs, filenames, short codes, etc. Optionally customizable.

Parameters
$wordlist : array<string|int, mixed>|null = null

Optional preloaded word list. Loads from /usr/share/dict/words by default.

$numberRange : int = 100

Max numeric suffix. Defaults to 100.

$separator : string = '-'

Separator between slug parts (e.g., '-', '_', '.'). Defaults to '-'.

$prefix : string = ''

Optional prefix string to prepend. No separator automatically added.

$suffix : string = ''

Optional suffix string to append. No separator automatically added.

Tags
example
Strings::randomSlugFromWordlist();                            // 'silent-sunset-42'
Strings::randomSlugFromWordlist(null, 999, '_');              // 'wild_cloud_314'
Strings::randomSlugFromWordlist(null, 100, '-', 'inv-', '-qa'); // 'inv-bold-stone-91-qa'
throws
Exception
Return values
string

Slug in the format: {$prefix}word{$sep}word{$sep}number{$suffix}

randomString()

Generates a cryptographically secure random string of a given length, optionally with a prefix.

public static randomString([int $length = 64 ][, string $prefix = '' ][, string $characterPool = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789' ]) : string

This method builds a random string using characters from the specified $characterPool. If a $prefix is provided, it is prepended to the result and counts toward the total length. The function ensures the final string is exactly $length characters long, trimming or limiting as needed. Uses random_int() to ensure cryptographic security.

Parameters
$length : int = 64

The total desired length of the output string, including prefix. Defaults to 64.

$prefix : string = ''

A string to prepend to the output. The remaining characters will be randomly generated.

$characterPool : string = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'

A string containing the characters to randomly choose from. Defaults to a URL-safe, unambiguous set (no 0, O, l, 1).

Tags
example
Strings::randomString(10);                       // e.g., 'a8B7jk3Mnp'
Strings::randomString(16, 'id_');                // e.g., 'id_7GkP8xLqJ93R'
Strings::randomString(5, '', 'ABC123');          // e.g., 'C1BA2'
edgecase

If $characterPool is empty or $length <= strlen($prefix), the method returns the prefix truncated or padded to the desired length.

note

This method uses PHP's random_int() and is cryptographically secure, making it suitable for tokens, nonces, session keys, or other security-sensitive purposes. However, it does not guarantee uniqueness. For universally unique identifiers, use a UUID generator.

throws
Exception
Return values
string

A random string of exactly $length characters, starting with $prefix if provided.

removeAccents()

Removes accents and diacritics from a UTF-8 string by converting to ASCII.

public static removeAccents(string $str) : string

This method uses iconv to transliterate accented characters to their closest ASCII equivalents (e.g., é → e, ü → u). Any remaining non-ASCII characters are stripped.

Parameters
$str : string

The input UTF-8 string.

Tags
example
Strings::removeAccents("Crème brûlée");     // "Creme brulee"
Strings::removeAccents("München");          // "Munchen"
Strings::removeAccents("façade");           // "facade"
note

This function removes all non-ASCII characters. Symbols like em-dashes (—) or smart quotes (“ ”) will be stripped.

Return values
string

The ASCII-safe, accent-stripped version of the input.

removeDuplicateWords()

Removes consecutive duplicate words in a string.

public static removeDuplicateWords(string $str) : string

Useful for cleaning up repeated input like "this this is is fine".

Parameters
$str : string

The input string.

Tags
example
Strings::removeDuplicateWords('this this is is a test');  // 'this is a test'
Return values
string

The cleaned string with duplicates removed.

removePrefix()

Removes the given prefix from the start of a string, if present.

public static removePrefix(string $str, string $prefix) : string

If the string begins with the specified prefix, it is removed. Otherwise, the original string is returned unchanged.

Parameters
$str : string

The input string to process.

$prefix : string

The prefix to remove if found at the beginning.

Tags
example
Strings::removePrefix('unhappy', 'un');       // 'happy'
Strings::removePrefix('hello world', 'hi');   // 'hello world' (unchanged)
Strings::removePrefix('abc123', 'abc');       // '123'
note

Comparison is case-sensitive. Use strtolower() if case-insensitive behavior is needed.

Return values
string

The string without the prefix (if removed).

removeSuffix()

Removes the given suffix from the end of a string, if present.

public static removeSuffix(string $str, string $suffix) : string

If the string ends with the specified suffix, it is removed. Otherwise, the original string is returned unchanged.

Parameters
$str : string

The input string to process.

$suffix : string

The suffix to remove if found at the end.

Tags
example
Strings::removeSuffix('filename.txt', '.txt');     // 'filename'
Strings::removeSuffix('report_final', '_final');   // 'report'
Strings::removeSuffix('document.PDF', '.pdf');     // 'document.PDF' (case-sensitive)
note

Comparison is case-sensitive. Use strtolower() or str_ends_with(strtolower(...)) if you need case-insensitive behavior.

Return values
string

The string without the suffix (if removed).

repeat()

Repeats a string a specified number of times.

public static repeat(string $str, int $times) : string

This method uses str_repeat() to duplicate the input string $times number of times. It returns the concatenated result. If $times is 0 or less, an empty string is returned.

Parameters
$str : string

The string to repeat.

$times : int

The number of times to repeat the string. Should be a non-negative integer.

Tags
example
Strings::repeat('abc', 3);     // 'abcabcabc'
Strings::repeat('*', 5);       // '*****'
Strings::repeat('xyz', 0);     // ''
edgecase

If $times is negative, str_repeat() returns an empty string without error. If $str is an empty string, the result will always be an empty string, regardless of $times.

note

This function does not trim or insert separators between repetitions. If you want space- or delimiter-separated repetitions, use a loop or implode().

Return values
string

The repeated string, or an empty string if $times is 0 or negative.

replaceFirstPartOfString()

Replaces the beginning of a string with a new prefix of the same length.

public static replaceFirstPartOfString(string $original, string $newFrontPiece) : string

This method replaces the first N characters of $original with the entire $newFrontPiece, where N is the length of $newFrontPiece. The rest of the original string remains unchanged.

Parameters
$original : string

The original string whose beginning will be replaced.

$newFrontPiece : string

The string that will replace the first part of $original. Its full length is used.

Tags
example
Strings::replaceFirstPartOfString('username123', 'admin');   // 'adminme123'
Strings::replaceFirstPartOfString('abcdef', 'XY');           // 'XYcdef'
edgecase

If $newFrontPiece is longer than $original, the result will include all of $newFrontPiece, followed by an empty string from substr(). This may result in truncation or unexpected output. If $newFrontPiece is an empty string, the result is identical to $original.

note

This is a low-level utility that performs raw byte-length replacement (via strlen() and substr()), not multibyte-safe. If working with UTF-8 strings containing multibyte characters, consider using mb_strlen() and mb_substr() for accuracy.

Return values
string

The resulting string with the beginning replaced by $newFrontPiece.

reverse()

Reverses a string safely with full multibyte (UTF-8) support.

public static reverse(string $str) : string

This is a Unicode-aware replacement for strrev(), which is not safe for multibyte characters. Useful for working with accented characters, non-Latin scripts, and emoji.

Parameters
$str : string

The input string to reverse.

Tags
example
Strings::reverse('hello');           // 'olleh'
Strings::reverse('áéíóú');           // 'úóíéá'
Strings::reverse('Доброе утро');     // 'орту еорбоД'
Strings::reverse('👩‍🚀💫🚀');           // '🚀💫👩‍🚀' (may break emoji clusters visually)
note

Uses mb_str_split() to correctly handle Unicode characters. Emoji or combining characters may not always render properly after reversal due to their complexity.

Return values
string

The reversed string.

reverseLines()

Reverses the order of lines in a multiline string.

public static reverseLines(string $str) : string

Splits the string on line breaks (handles LF, CRLF, and CR), reverses the order of lines, and rejoins them using the original line break format where possible.

Parameters
$str : string

The input multiline string.

Tags
example
Strings::reverseLines("line 1\nline 2\nline 3");
// "line 3\nline 2\nline 1"
note

Handles LF (\n), CRLF (\r\n), and CR (\r) line endings. Output will use the same line endings as the input.

Return values
string

The string with lines in reverse order.

reverseWords()

Reverses the order of words in a string while preserving the words themselves.

public static reverseWords(string $str) : string

Splits the string by whitespace (spaces, tabs, newlines), reverses the order of the words, and joins them back together with a single space.

Parameters
$str : string

The input string containing words.

Tags
example
Strings::reverseWords('The quick brown fox');   // 'fox brown quick The'
Strings::reverseWords('Привет мир');            // 'мир Привет'
note

Whitespace is normalized to single spaces in the output. Multibyte characters are fully supported. Punctuation stays attached to words (e.g., 'hello!' becomes 'hello!').

Return values
string

The string with word order reversed.

rot13()

Applies the ROT13 cipher to a string.

public static rot13(string $str) : string

Replaces each letter with the one 13 positions ahead in the alphabet. Non-alphabetic characters are left unchanged. Case is preserved.

Parameters
$str : string

The input string.

Tags
example
Strings::rot13('Hello');  // 'Uryyb'
Strings::rot13('Uryyb');  // 'Hello'
Return values
string

The ROT13-encoded string.

safeHtml()

Escapes special characters in a string for safe output in HTML.

public static safeHtml(string $str) : string

This method converts characters like <, >, &, ", and ' into their HTML-encoded equivalents to prevent XSS (Cross-Site Scripting) attacks or HTML injection. It uses htmlspecialchars() with ENT_QUOTES | ENT_SUBSTITUTE and UTF-8 encoding for broad compatibility and safety.

Parameters
$str : string

The raw input string to escape for HTML output.

Tags
example
Strings::safeHtml('<script>alert("XSS")</script>'); // '&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;'
Strings::safeHtml("Tom & Jerry's \"Cat\"");         // 'Tom &amp; Jerry&#039;s &quot;Cat&quot;'
edgecase

If the string contains invalid UTF-8 sequences, ENT_SUBSTITUTE ensures they are replaced with a Unicode replacement character () rather than causing encoding errors or breaking output.

note

This method escapes both double and single quotes (ENT_QUOTES), making it safe for use in attribute values. Always use this (or similar escaping) when inserting untrusted content into HTML pages.

Return values
string

A safely escaped string suitable for embedding in HTML.

sanitizeFilename()

Sanitizes a string for use as a safe filename by replacing disallowed characters with underscores.

public static sanitizeFilename(string $str) : string

This method replaces any character that is not a letter, digit, underscore (_), hyphen (-), or dot (.) with an underscore. It helps prevent issues with file systems, URLs, or uploads that reject unsafe characters.

Parameters
$str : string

The input string to sanitize.

Tags
example
Strings::sanitizeFilename('My Report (Final).pdf');    // 'My_Report__Final_.pdf'
Strings::sanitizeFilename('user@domain.com');          // 'user_domain.com'
Strings::sanitizeFilename('file name*&^%.txt');        // 'file_name____.txt'
edgecase

If the input contains only disallowed characters, the result will be all underscores. This method does not collapse consecutive underscores or trim the result — it is literal.

note

This method does not check for reserved filenames (like CON, NUL, or COM1 on Windows), nor does it enforce length limits. Consider additional validation if targeting specific filesystems.

Return values
string

A filename-safe version of the input string.

sanitizeHex()

Validates and normalizes a hexadecimal string.

public static sanitizeHex(string $hex[, bool $toUpper = false ]) : string|null

If the input is a valid hexadecimal string (optionally with a "0x"/"0X" prefix), returns the normalized hex string (prefix removed, casing standardized). If the input is invalid, returns null.

Parameters
$hex : string

The input hex string to validate and sanitize.

$toUpper : bool = false

Whether to return the result in uppercase. Default is false (lowercase).

Tags
example
Strings::sanitizeHex('0xABC123');        // 'abc123'
Strings::sanitizeHex('ABC123', true);    // 'ABC123'
Strings::sanitizeHex('g123');            // null
note

This method combines isHex() and normalizeHex() with prefix support.

Return values
string|null

The cleaned hex string, or null if invalid.

sentenceCount()

Counts the number of sentences in a string.

public static sentenceCount(string $str) : int

A sentence is defined as ending with a period (.), question mark (?), or exclamation point (!), followed by a space or end of string.

Parameters
$str : string

The input text.

Tags
example
Strings::sentenceCount('This is one. And another!');  // 2
Return values
int

Number of sentences found.

shuffle()

Randomly shuffles the characters in a multibyte string.

public static shuffle(string $str) : string

Splits the string into an array of characters, randomizes the order using shuffle(), and returns the resulting string. Useful for non-critical randomness (e.g., games, CAPTCHAs).

Parameters
$str : string

The input string to shuffle.

Tags
example
Strings::shuffle('hello');        // might return 'lohel', 'elhol', etc.
Strings::shuffle('áéíóú');        // preserves multibyte characters correctly
note

This is not cryptographically secure. Do not use for password generation or security tokens. Multibyte-safe via mb_str_split().

Return values
string

The string with its characters randomly reordered.

signHmac()

Generates an HMAC signature for a payload using the given key and algorithm.

public static signHmac(string $payload, string $key[, string $algo = 'sha256' ]) : string

Useful for API authentication or secure data signing.

Parameters
$payload : string

The message to sign.

$key : string

The secret key.

$algo : string = 'sha256'

The hashing algorithm to use. Default is 'sha256'.

Tags
example
Strings::signHmac('data', 'secret');             // 'aabbcc...'
Strings::signHmac('payload', 'key', 'sha1');     // SHA1 HMAC
Return values
string

The generated HMAC hash as a hex string.

similarity()

Calculates the percentage similarity between two strings.

public static similarity(string $a, string $b) : float

This method uses PHP’s similar_text() function to determine how similar two strings are, returning a float percentage from 0 to 100 representing their likeness.

Parameters
$a : string

The first string to compare.

$b : string

The second string to compare.

Tags
example
Strings::similarity('apple', 'apples');      // 91.666...
Strings::similarity('hello', 'yellow');      // 60.0
Strings::similarity('cat', 'dog');           // 0.0
edgecase

An empty string compared with another string results in 0.0. Case differences are treated as mismatches — the comparison is case-sensitive.

note

This function uses a time-consuming algorithm for long strings, as similar_text() has O(N^3) complexity. For faster or fuzzy comparisons, consider levenshtein() or external string similarity libraries.

Return values
float

A similarity percentage between 0 and 100, where 100 means the strings are identical.

slugify()

Converts a string into a URL-friendly "slug" format.

public static slugify(string $str) : string

This method transforms the input string to lowercase, replaces all non-alphanumeric characters with hyphens, and trims any leading or trailing hyphens. It's commonly used to create clean, SEO-friendly URL segments.

Parameters
$str : string

The input string to convert into slug form.

Tags
example
Strings::slugify('Hello World!');        // 'hello-world'
Strings::slugify('PHP & MySQL Tips');    // 'php-mysql-tips'
Strings::slugify('  Leading/Trailing  '); // 'leading-trailing'
edgecase

If the input string is empty or contains no alphanumeric characters, the return value will be an empty string.

note

Only basic ASCII characters are handled. Accented characters (e.g., é, ñ) will be removed rather than converted. To support Unicode or transliteration, additional normalization steps (e.g., iconv(), transliterator_transliterate()) would be required.

Return values
string

A slugified version of the string, containing only lowercase letters, digits, and hyphens. Consecutive non-alphanumeric characters are replaced by a single hyphen.

slugToTitle()

Converts a slug-formatted string into a human-readable title case string.

public static slugToTitle(string $slug) : string

This method replaces hyphens and underscores with spaces and then applies title casing. It is useful for transforming URL-friendly slugs (e.g., my-awesome-title) into readable titles (e.g., My Awesome Title).

Parameters
$slug : string

The slug string to convert. Typically lowercase, words separated by - or _.

Tags
example
Strings::slugToTitle('my-awesome-title');     // 'My Awesome Title'
Strings::slugToTitle('another_example_here'); // 'Another Example Here'
Strings::slugToTitle('mixed-separators_here'); // 'Mixed Separators Here'
edgecase

If the slug is an empty string, the result will also be an empty string. If the slug contains characters beyond alphanumerics, dashes, or underscores, they will remain in the result unless handled by titleCase().

note

This function depends on self::titleCase() for casing logic. If titleCase() has locale-specific behavior or Unicode quirks, those will affect the output of this method as well.

Return values
string

A title-cased version of the input, with separators replaced by spaces.

smartTitleCase()

Converts a string to title case while preserving acronyms and lowercasing stop words.

public static smartTitleCase(string $str[, array<string|int, mixed> $acronyms = ['ID', 'HTML', 'CSS', 'PHP', 'NASA', 'API', 'URL', 'JSON'] ][, array<string|int, mixed> $stopWords = ['and', 'or', 'but', 'for', 'nor', 'a', 'an', 'the', 'in', 'on', 'at', 'to', 'by', 'of', 'with'] ]) : string

Capitalizes each word unless:

  • It's a known acronym (e.g., NASA, PHP), which stays uppercase
  • It's a stop word (e.g., and, the, in), which remains lowercase — unless it's the first word
Parameters
$str : string

The input string to convert.

$acronyms : array<string|int, mixed> = ['ID', 'HTML', 'CSS', 'PHP', 'NASA', 'API', 'URL', 'JSON']

Acronyms to preserve in uppercase. Default includes common technical acronyms.

$stopWords : array<string|int, mixed> = ['and', 'or', 'but', 'for', 'nor', 'a', 'an', 'the', 'in', 'on', 'at', 'to', 'by', 'of', 'with']

Stop words to keep lowercase unless at the start. Default includes common English stop words.

Tags
example
Strings::smartTitleCase('introduction to php and html');
// 'Introduction to PHP and HTML'

Strings::smartTitleCase('the future of ai in nasa');
// 'The Future of AI in NASA'
Return values
string

The smartly title-cased string.

snake_case()

Converts a string into snake_case format.

public static snake_case(string $str) : string

This method replaces all sequences of non-letter and non-number characters with underscores, trims leading/trailing underscores, and lowercases the result. It uses a Unicode-aware regex, making it suitable for international input as well.

Parameters
$str : string

The input string to convert. Can contain spaces, punctuation, symbols, etc.

Tags
example
Strings::snake_case('Hello World!');           // 'hello_world'
Strings::snake_case('already_snake_case');     // 'already_snake_case'
Strings::snake_case('Multiple---delimiters');  // 'multiple_delimiters'
Strings::snake_case('Ünicode & Symbols ™️');   // 'ünicode_symbols'
edgecase

Input with only non-alphanumeric characters (e.g., '!!!') will result in an empty string after trimming. Multiple adjacent non-word characters are collapsed into a single underscore.

note

This function uses Unicode character classes (\p{L} for letters, \p{N} for numbers) and requires the u modifier to properly handle multibyte input. If the mbstring or pcre extension is misconfigured or missing, results may be unreliable.

Return values
string

A snake_cased version of the string, consisting of lowercase letters, numbers, and underscores.

startsWith()

Checks whether a string starts with a given substring.

public static startsWith(string $haystack, string $needle) : bool

This method determines if $haystack begins with the specified $needle. It uses strncmp() to compare the start of $haystack with $needle up to the length of $needle.

Parameters
$haystack : string

The full string to evaluate.

$needle : string

The substring to check for at the start of $haystack.

Tags
example
Strings::startsWith('hello world', 'hello'); // true
Strings::startsWith('hello world', 'Hello'); // false (case-sensitive)
Strings::startsWith('abc', '');              // true (empty needle)
edgecase

If $needle is an empty string, the function will return true regardless of $haystack. This may be unintuitive but is consistent with how prefix checks are typically defined.

note

This function is case-sensitive. If you need case-insensitive behavior, consider converting both strings to lowercase before comparison (e.g., using strtolower()).

Return values
bool

Returns true if $haystack starts with $needle, otherwise false.

startsWithAny()

Checks whether the given string starts with any of the specified prefixes.

public static startsWithAny(string $haystack, array<string|int, mixed> $prefixes) : bool

Iterates through an array of possible prefixes and returns true as soon as one matches the beginning of the input string.

Parameters
$haystack : string

The string to check.

$prefixes : array<string|int, mixed>

An array of string prefixes to test against.

Tags
example
Strings::startsWithAny('circle6maildrop.com', ['https://', 'circle']);     // true
Strings::startsWithAny('example.txt', ['test', 'demo']);                   // false
note

Comparison is case-sensitive. Use strtolower() on both haystack and prefixes if you need case-insensitive behavior.

Return values
bool

True if the string starts with any prefix in the array; false otherwise.

strip()

Removes all occurrences of the specified characters from a string.

public static strip(string $str, array<string|int, mixed> $chars) : string

This method uses str_replace() to remove every instance of each character (or substring) listed in the $chars array from the input string. It is a simple way to filter out unwanted characters.

Parameters
$str : string

The input string to clean.

$chars : array<string|int, mixed>

An array of characters or substrings to remove from the input.

Tags
example
Strings::strip('hello world', ['l', ' ']);     // 'heoworld'
Strings::strip('(123) 456-7890', ['(', ')', '-', ' ']); // '1234567890'
Strings::strip('abcXYZ123', ['a', '1', 'Z']);  // 'bcXY23'
edgecase

If $chars is an empty array, the input string is returned unchanged. If any of the values in $chars are longer substrings (e.g., 'abc'), entire matches will be removed.

note

This function performs exact, case-sensitive replacements. If you need case-insensitive stripping, consider normalizing the input and $chars array to lowercase or using str_ireplace().

Return values
string

The resulting string after all specified characters/substrings are removed.

stripDiacritics()

Removes diacritical marks (accents) from characters while preserving the base letter.

public static stripDiacritics(string $str) : string

For example: é → e, ü → u, ñ → n.

Parameters
$str : string

The input string.

Tags
example
Strings::stripDiacritics("Crème brûlée");  // 'Creme brulee'
Return values
string

The de-accented string.

stripHtmlButAllow()

Strips all HTML tags from a string except those explicitly allowed.

public static stripHtmlButAllow(string $str[, string $allowedTags = '<b><i><br>' ]) : string

This method uses strip_tags() to remove all HTML and PHP tags from the input string, while optionally preserving a whitelist of specified tags. Useful when sanitizing user input while still permitting basic formatting (e.g., <b>, <i>, <br>).

Parameters
$str : string

The input string potentially containing HTML.

$allowedTags : string = '<b><i><br>'

A string of allowed tags in angle brackets (e.g., '<b><i><br>'). Tags must be lowercase and well-formed to be preserved.

Tags
example
Strings::stripHtmlButAllow('<b>Hello</b> <script>bad()</script>', '<b>'); // '<b>Hello</b> bad()'
Strings::stripHtmlButAllow('<i>Italic</i><br><u>Underlined</u>', '<i><br>'); // '<i>Italic</i><br>Underlined'
Strings::stripHtmlButAllow('No HTML at all'); // 'No HTML at all'
edgecase

The $allowedTags string must use lowercase tag names — uppercase versions will not match and will be stripped. Any tag not listed exactly (e.g., <BR> or <i class="foo">) will be stripped, even if visually similar.

note

This method does not validate or close malformed HTML. It simply removes disallowed tags without restructuring the DOM. For stricter or more sophisticated HTML filtering, consider using a dedicated HTML purifier library.

Return values
string

The sanitized string with only the allowed tags preserved.

stripNonPrintable()

Removes all non-printable (control) characters from a string.

public static stripNonPrintable(string $str) : string

Uses the Unicode \P{C} property to retain only printable characters. This includes visible characters, whitespace, and multibyte characters, but strips out control codes like newlines, null bytes, bell characters, etc.

Parameters
$str : string

The input string to sanitize.

Tags
example
Strings::stripNonPrintable("abc\x00\x1Fdef");   // 'abcdef'
Strings::stripNonPrintable("Hello\nWorld");     // 'HelloWorld'
Strings::stripNonPrintable("🚀 Launch!");        // '🚀 Launch!' (unchanged)
note

This method is Unicode-aware and multibyte-safe. Whitespace such as spaces and tabs are preserved.

Return values
string

The cleaned string with only printable characters remaining.

stripPunctuation()

Removes all punctuation characters from a string, preserving letters, numbers, and whitespace.

public static stripPunctuation(string $str) : string

Useful for search indexing or cleaning input text.

Parameters
$str : string

The input string.

Tags
example
Strings::stripPunctuation("Hello, world!");  // 'Hello world'
Return values
string

The string with punctuation removed.

titleCase()

Converts a string to title case using multibyte-safe logic.

public static titleCase(string $str) : string

This method uses mb_convert_case() with the MB_CASE_TITLE mode to capitalize the first letter of each word, while converting the rest to lowercase. It supports UTF-8 encoded strings and is safe for multibyte characters.

Parameters
$str : string

The input string to convert to title case.

Tags
example
Strings::titleCase('hello world');        // 'Hello World'
Strings::titleCase('mULTIbYTE çharacters'); // 'Multibyte Çharacters'
Strings::titleCase('123 go!');            // '123 Go!'
edgecase

Words that start with non-letter characters (e.g., numbers or punctuation) will remain unchanged at the beginning, and only subsequent alphabetic characters will be affected.

note

This function uses mb_convert_case() with 'UTF-8' encoding and requires the mbstring extension. It lowercases the rest of each word — so acronyms or intentional capitalization (e.g., “iPhone”) may be normalized.

Return values
string

The title-cased version of the input string.

toAscii()

Converts a UTF-8 string to an ASCII-only representation by transliterating accented and special characters.

public static toAscii(string $str) : string

This method uses iconv() with the TRANSLIT and IGNORE flags to attempt conversion of multibyte characters into their closest ASCII equivalents (e.g., üu, ñn). Characters that cannot be transliterated are dropped.

Parameters
$str : string

The UTF-8 encoded input string to convert.

Tags
example
Strings::toAscii('Jalapeño');     // 'Jalapeno'
Strings::toAscii('français');     // 'francais'
Strings::toAscii('naïve café');   // 'naive cafe'
edgecase

Characters that cannot be represented in ASCII and are not translatable will be silently discarded. If the input string is already ASCII, the result will be identical.

note

This function depends on the iconv extension. If iconv() is not available or fails, it may return false or an empty string, depending on the PHP environment. Also, behavior of transliteration may vary slightly across systems or locales.

Return values
string

The ASCII-only version of the input string, with accents and special characters removed or replaced.

toAsciiSafe()

Converts a string to ASCII by transliterating or removing non-ASCII characters.

public static toAsciiSafe(string $str[, string $replacement = '' ]) : string

Uses iconv() to transliterate characters like "é" → "e", "ü" → "u", etc. Falls back to stripping any remaining multibyte characters not handled by transliteration.

Parameters
$str : string

The input string to sanitize.

$replacement : string = ''

Optional string to insert in place of untranslatable characters. Default is empty string.

Tags
example
Strings::toAsciiSafe('Café');              // 'Cafe'
Strings::toAsciiSafe('Grüße aus München'); // 'Grusse aus Munchen'
Strings::toAsciiSafe('👋🌍');               // '' (emoji are removed)
note

iconv() may behave differently across platforms. Remaining non-ASCII characters are stripped using a regex cleanup.

Return values
string

A best-effort ASCII-safe version of the input.

toCamelCase()

Converts a string to camelCase.

public static toCamelCase(string $str) : string

Removes separators (space, dash, underscore), capitalizes each word, and lowercases the first character.

Parameters
$str : string

The input string.

Tags
example
Strings::toCamelCase('user name');      // 'userName'
Strings::toCamelCase('hello_world');    // 'helloWorld'
Return values
string

The camelCased string.

toggleCase()

Toggles the case of each character in a string.

public static toggleCase(string $str) : string

This method loops through each character of the input string, converting uppercase letters to lowercase and lowercase letters to uppercase. Non-alphabetic characters are left unchanged.

Parameters
$str : string

The input string to toggle.

Tags
example
Strings::toggleCase('Hello World');   // 'hELLO wORLD'
Strings::toggleCase('123abcABC');     // '123ABCabc'
Strings::toggleCase('!@#');           // '!@#' (unchanged)
edgecase

Multibyte characters (e.g., accented or non-Latin characters) are not supported correctly, since str_split() and ctype_upper() operate on single bytes. Characters like é or ß may be split incorrectly or ignored.

note

This function is not multibyte safe. For Unicode-safe case toggling, a more robust approach using mb_* functions and normalization would be needed.

Return values
string

A new string with the case of each letter inverted.

toKebabCase()

Converts a string to kebab-case.

public static toKebabCase(string $str) : string

Converts spaces, camelCase, and underscores into hyphens.

Parameters
$str : string

The input string.

Tags
example
Strings::toKebabCase('HelloWorld');     // 'hello-world'
Strings::toKebabCase('user_name');      // 'user-name'
Return values
string

The kebab-cased string.

toSlugId()

Converts a string to a slug and appends an identifier, forming a slug-ID composite string.

public static toSlugId(string $str, int|string $id) : string

This method applies slugify() to the input string to generate a URL-friendly slug, then appends a hyphen followed by the provided $id. It is commonly used for creating SEO-friendly URLs that include both readable text and a unique identifier.

Parameters
$str : string

The input string to convert into a slug.

$id : int|string

The identifier to append. Typically a numeric ID, but any scalar value can be used.

Tags
example
Strings::toSlugId('Hello World', 42);         // 'hello-world-42'
Strings::toSlugId('Ünicode Title', 'abc123'); // 'unicode-title-abc123'
edgecase

If $str results in an empty slug (e.g., if it only contains symbols), the result will be -$id. If $id is not scalar, it will be coerced to string, which may produce unintended output (e.g., 'Array' or 'Object').

note

This method relies on self::slugify(), which removes special characters and collapses whitespace. Be sure to validate or sanitize $id if used in URLs or filenames.

Return values
string

The combined slug and ID string, formatted as slugified-string-id.

toSnakeCase()

Converts a string to snake_case.

public static toSnakeCase(string $str) : string

Replaces spaces and camelCase boundaries with underscores.

Parameters
$str : string

The input string.

Tags
example
Strings::toSnakeCase('HelloWorld');     // 'hello_world'
Strings::toSnakeCase('user name');      // 'user_name'
Return values
string

The snake_cased string.

toTitleCase()

Converts a string to title case, capitalizing the first letter of each word.

public static toTitleCase(string $str) : string

Supports multibyte characters and Unicode scripts. Uses mb_convert_case() with MB_CASE_TITLE.

Parameters
$str : string

The input string to convert.

Tags
example
Strings::toTitleCase('the quick brown fox');     // 'The Quick Brown Fox'
Strings::toTitleCase('grüße aus münchen');       // 'Grüße Aus München'
Return values
string

The title-cased version of the input.

truncate()

Truncates a string to a specified length and appends an ellipsis (or other trailing marker).

public static truncate(string $string, int $length[, string $ellipsis = '…' ]) : string

This method uses multibyte-safe functions to truncate $string to the desired $length, including space for the $ellipsis if the original string exceeds that length. If the string is already within the limit, it is returned unchanged.

Parameters
$string : string

The input string to truncate.

$length : int

The maximum length of the returned string, including the ellipsis. Must be at least as long as the ellipsis itself.

$ellipsis : string = '…'

The string to append to the end of truncated text. Defaults to a single Unicode ellipsis character ().

Tags
example
Strings::truncate('This is a long sentence.', 10);           // 'This is a…'
Strings::truncate('Short text', 20);                         // 'Short text'
Strings::truncate('Multibyte 💡 text here', 15);             // 'Multibyte 💡…'
Strings::truncate('Cut mid-word test', 7, '...');            // 'Cut...'
edgecase

If $length is less than or equal to the length of $ellipsis, the function may return just a portion of the ellipsis or an empty string. This can lead to unexpected results. Example: truncate('test', 2, '...') returns '.'.

note

This method uses mb_strlen() and mb_substr() for proper multibyte (e.g., UTF-8) character handling. If your environment lacks the mbstring extension, it may produce incorrect behavior.

Return values
string

The truncated string, with the ellipsis appended if truncation occurred.

ulid()

Generates a ULID (Universally Unique Lexicographically Sortable Identifier).

public static ulid([bool $uppercase = true ]) : string

A ULID is a 26-character Base32-encoded string composed of:

  • 48 bits: timestamp (in milliseconds since Unix epoch)
  • 80 bits: cryptographically secure random data

It sorts lexicographically and is safe for use in filenames, URLs, database keys, and logs.

Parameters
$uppercase : bool = true

Whether to return the ULID in uppercase (default) or lowercase.

Tags
example
Strings::ulid();                              // e.g., '01HZX7RCEJMBFZZC1P4EW6Q7NH'
Strings::ulid(1700000000000);                 // ULID with a fixed timestamp
Strings::ulid(null, false);                   // Lowercase ULID using current timestamp
Strings::ulid(1700000000000, false);          // '01hzb5xq4rg23ndgjtw4ht9q4f'
throws
Exception
Return values
string

A 26-character ULID string.

ulidTimestamp()

Extracts the timestamp (in milliseconds since Unix epoch) from a ULID string.

public static ulidTimestamp(string $ulid) : int

The first 10 characters of a ULID encode a 48-bit timestamp using Crockford Base32. This method decodes it back into an integer Unix timestamp in milliseconds.

Parameters
$ulid : string

A valid 26-character ULID string.

Tags
throws
InvalidArgumentException

If the input is not a valid ULID.

example
$ulid = Strings::ulid(1700000000000);
$ms = Strings::ulidTimestamp($ulid); // 1700000000000
Return values
int

The timestamp in milliseconds since epoch.

ulidTimestampToDateTime()

Extracts the timestamp from a ULID and returns it as a DateTimeImmutable object.

public static ulidTimestampToDateTime(string $ulid) : DateTimeImmutable

This is useful for converting a ULID into a human-readable or formatted datetime.

Parameters
$ulid : string

A valid 26-character ULID.

Tags
throws
InvalidArgumentException

If the ULID is not valid.

throws
Exception
example
$ulid = Strings::ulid(); // e.g., '01HZX7RCEJMBFZZC1P4EW6Q7NH'
$dt = Strings::ulidTimestampToDateTime($ulid);
echo $dt->format('Y-m-d H:i:s'); // e.g., "2023-11-14 21:33:20"
Return values
DateTimeImmutable

A UTC DateTimeImmutable representing the ULID's timestamp.

uuid()

Generates a RFC 4122–compliant UUID (version 4), with optional casing.

public static uuid([bool $uppercase = true ]) : string

UUID v4 format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx

  • 4 indicates version 4 (random-based)
  • y is one of 8, 9, A, or B (variant 1)
Parameters
$uppercase : bool = true

If true (default), returns UUID in uppercase. If false, returns lowercase.

Tags
example
Strings::uuid();              // '3F6C0A7E-9F57-42DB-9A73-91F3A984D317'
Strings::uuid(false);         // '3f6c0a7e-9f57-42db-9a73-91f3a984d317'
throws
Exception
Return values
string

A 36-character UUID v4 string.

uuidv7()

Generates a UUID version 7 (time-ordered + random) based on the draft UUIDv7 spec.

public static uuidv7([bool $uppercase = true ]) : string

UUIDv7 uses:

  • 48 bits: milliseconds since Unix epoch
  • 12 bits: version and partial randomness
  • 62 bits: additional randomness

This format is ideal for systems that require globally unique, time-sortable identifiers.

Parameters
$uppercase : bool = true

Whether to return the UUID in uppercase. Defaults to true.

Tags
example
Strings::uuidv7();        // '017F22E2-79B0-7CC3-98C4-DC0C0C07398F'
Strings::uuidv7(false);   // '017f22e2-79b0-7cc3-98c4-dc0c0c07398f'
throws
Exception
Return values
string

A 36-character RFC-style UUIDv7 string.

verifyHmacSignature()

Verifies an HMAC signature against a message and secret key using a constant-time comparison.

public static verifyHmacSignature(string $payload, string $signature, string $secret[, string $algo = 'sha256' ][, bool $isBase64 = false ]) : bool

This is useful for authenticating webhooks or signed payloads. It securely compares the provided signature with a locally generated one, avoiding timing attacks.

Parameters
$payload : string

The raw message or data (e.g., webhook body).

$signature : string

The HMAC signature to verify (hex or base64).

$secret : string

The shared secret key used to generate the original signature.

$algo : string = 'sha256'

Hashing algorithm to use (e.g. 'sha256', 'sha1'). Default is 'sha256'.

$isBase64 : bool = false

Whether the signature is base64-encoded instead of hex.

Tags
example
// Verifying a GitHub-style HMAC signature:
Strings::verifyHmacSignature($json, $_SERVER['HTTP_X_HUB_SIGNATURE_256'], $secret, 'sha256');
Return values
bool

True if the signature is valid; false otherwise.

verifyTwilioSignature()

Verifies a Twilio webhook signature.

public static verifyTwilioSignature(string $url, array<string|int, mixed> $params, string $signature, string $authToken) : bool

Reconstructs Twilio’s signing scheme by combining the request URL and sorted POST params, then validates the Base64 HMAC-SHA1 signature against the X-Twilio-Signature header.

Parameters
$url : string

The full request URL (no query string).

$params : array<string|int, mixed>

The POST parameters (from $_POST).

$signature : string

The value of X-Twilio-Signature header.

$authToken : string

Your Twilio auth token.

Tags
example
Strings::verifyTwilioSignature(
    'https://example.com/handler',
    $_POST,
    $_SERVER['HTTP_X_TWILIO_SIGNATURE'],
    getenv('TWILIO_AUTH_TOKEN')
);
Return values
bool

True if the signature matches; false otherwise.

wordCount()

Counts the number of words in a string, ignoring any HTML tags.

public static wordCount(string $str) : int

This method first strips all HTML tags from the input using strip_tags(), then counts the remaining words using str_word_count(). A "word" is any sequence of characters considered a word by str_word_count(), which primarily matches ASCII letter sequences.

Parameters
$str : string

The input string to analyze. Can include HTML.

Tags
example
Strings::wordCount('Hello world!');                       // 2
Strings::wordCount('<p>Hello <strong>world</strong></p>'); // 2
Strings::wordCount('Él vive en México.');                 // 4 (may vary if multibyte-aware logic is needed)
edgecase

str_word_count() may undercount or skip words that contain accented characters, emojis, or characters outside the basic ASCII range unless locale settings are adjusted. HTML entities like &amp; are preserved and may count as words depending on context.

note

This method is not multibyte-aware and may give inaccurate results for non-English or non-ASCII content. For full Unicode-aware word counting, consider using preg_match_all() with a Unicode word boundary regex.

Return values
int

The number of words in the plain-text version of the string.

wordWrapHtmlSafe()

Wraps long text inside HTML content without breaking tags.

public static wordWrapHtmlSafe(string $str[, int $width = 75 ][, string $break = " " ]) : string

This method applies wordwrap() only to text content found between HTML tags, preserving the structure of the HTML while wrapping visible text at the specified width. It avoids breaking tags or inserting line breaks within HTML elements.

Parameters
$str : string

The HTML-containing string to wrap.

$width : int = 75

The maximum line width before inserting a break. Defaults to 75 characters.

$break : string = " "

The string to insert as the break. Defaults to a newline character ("\n").

Tags
example
Strings::wordWrapHtmlSafe('<p>This is a very long sentence that needs to wrap properly within HTML.</p>', 20);
// '<p>This is a very long\nsentence that needs to\nwrap properly within\nHTML.</p>'
edgecase

Only visible text between tags is affected. Content inside tags like <script> or <style> may not be handled as expected. Text inside attributes (e.g., title="...") is not affected or wrapped. If the HTML is malformed (e.g., unclosed tags), behavior may be unpredictable.

note

This function uses a regular expression to match content between > and <, so it assumes reasonably well-formed HTML. It's designed for basic formatting tasks — not for deeply nested or edge-case HTML.

Return values
string

The HTML string with visible text word-wrapped, leaving tags untouched.

wrap()

Wraps a string with a given prefix and suffix.

public static wrap(string $str, string $prefix, string $suffix) : string

This method prepends the specified $prefix and appends the $suffix to the input string. It is useful for surrounding content with quotation marks, brackets, tags, or other markers.

Parameters
$str : string

The input string to wrap.

$prefix : string

The string to prepend.

$suffix : string

The string to append.

Tags
example
Strings::wrap('value', '[', ']');         // '[value]'
Strings::wrap('text', '"', '"');          // '"text"'
Strings::wrap('hello', '<b>', '</b>');    // '<b>hello</b>'
edgecase

If $str is an empty string, only the prefix and suffix are returned (e.g., wrap('', '[', ']')'[]'). If either $prefix or $suffix is empty, only the non-empty part is added.

note

This method does not escape or validate the input or wrappers — it's a raw string operation.

Return values
string

The resulting string with $prefix and $suffix added.


        
On this page

Search results