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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
stringhasMixedCase()
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Return values
string —The resulting string with $prefix
and $suffix
added.