strings
Table of Contents
Namespaces
Functions
- append() : string
- Append one or more suffix strings to the given source string, then normalize the result.
- between() : string
- Encapsulates an expression between specific characters.
- betweenBraces() : string
- Encapsulates an expression between braces '{..}'
- betweenBrackets() : string
- Encapsulates an expression between brackets '[..]'
- betweenDoubleQuotes() : string
- Wraps an expression in double quotes or a custom character.
- betweenParentheses() : string
- Encapsulates an expression between parentheses (`()`).
- betweenQuotes() : string
- Wraps an expression in quotes or a custom character.
- betweenSpaces() : string
- Wraps an expression with spaces on both sides.
- block() : string
- Format an indented multi-line text block.
- blockPrefix() : string
- Prefix and indent each line of a multi-line string or array of lines.
- blockSuffix() : string
- Suffix and indent each line of a multi-line string or array of lines.
- camel() : string
- Converts a string to camelCase format.
- compile() : string
- Compiles a string, object, boolean, or an array of expressions into a single string.
- dotKebab() : string
- Converts a camelCase or PascalCase string into a format where the first word is separated by a dot (.) from the rest, which are joined using kebab-case (-).
- fastFormat() : string
- Quickly formats a string using indexed placeholders and arguments.
- format() : string
- Format a template string using an external document.
- formatFromDocument() : string
- Format a template string using key-value pairs from an array or object.
- formatQuotedString() : string
- Formats a string value with proper escaping and wrapping using the specified quote style.
- formatRequestArgs() : string
- Builds a query string (`?key=value&...`) from an associative array.
- func() : string
- Generates a function expression like `NAME(arg1,arg2)`.
- hyphenate() : string
- Converts a camelCase or PascalCase string to a hyphenated (kebab-case) string.
- isQuote() : bool
- Checks if a character is a known quote character.
- isRegexp() : bool
- Determines whether a given string is a valid regular expression pattern.
- kebab() : string
- Converts a camelCase or PascalCase string into kebab-case (lowercase with hyphens).
- key() : string
- Returns a transformed key by optionally prepending a prefix.
- keyValue() : string
- Build a key-value expression like `key: value`.
- latinize() : string
- Converts a string by replacing accented Latin characters with their ASCII equivalents.
- lower() : string
- Converts a string to lowercase using multibyte-safe methods when possible.
- luhn() : bool
- Validates whether a given string is a valid Luhn code (mod 10 checksum).
- object() : string
- Generate a JavaScript-like object string.
- pad() : string
- Pads a UTF-8 string to a certain length using a specified padding string and type.
- padBoth() : string
- Pads a UTF-8 string on both sides (left and right) to a certain length using a specified padding string.
- padEnd() : string
- Pads a UTF-8 string on the right (end) to a certain length using a specified padding string.
- padStart() : string
- Pads a UTF-8 string on the left (start) to a certain length using a specified padding string.
- predicate() : string
- Generate a predicate expression as a string.
- predicates() : string|null
- Generate a complex logical expression with multiple predicates.
- prepend() : string
- Prepend one or more prefix strings to the given source string, then normalize the result.
- randomKey() : string
- Generates a random key string, optionally prefixed with a given string and separated by a custom separator.
- slice() : string
- Extracts a substring from a UTF-8 encoded string using grapheme clusters, which ensures multi-byte characters (like emojis, accented letters) are not broken.
- snake() : string
- Converts a string to snake_case (or a custom delimiter).
- toPhpHumanReadableScalar() : string
- Converts a scalar value (string, boolean, float, etc.) to a simplified, human-readable PHP string representation.
- toPhpString() : string
- Converts any PHP value into a valid PHP code string representation.
- convert() : string
- Recursively converts any PHP value into a PHP code string representation.
- convertObject() : string
- Converts an object to a PHP string representation with customizable formatting.
- convertArray() : string
- Converts an associative or sequential PHP array into a human-readable PHP string representation.
- toString() : string
- Converts a value to a string representation.
- urlencode() : string
- Encodes the specified URI according to RFC 3986.
- wrap() : string
- Wrap a string with a given character.
- wrapBlock() : string
- Wraps a block of lines with a header and footer line.
Functions
append()
Append one or more suffix strings to the given source string, then normalize the result.
append(string|null $source, string ...$suffix) : string
If the source string is null, returns an empty string. If multiple suffixes are provided, they are concatenated before appending. The resulting string is normalized using Unicode Normalization Form C (NFC).
Parameters
- $source : string|null
-
The original string or null.
- $suffix : string
-
One or more suffix strings to append.
Tags
Return values
string —The normalized concatenation of source and suffix(es).
between()
Encapsulates an expression between specific characters.
between([mixed $expression = null ][, string $left = '' ][, string|null $right = null ][, bool $flag = true ][, string $separator = ' ' ][, bool $trim = true ]) : string
Wraps the expression with $left
and $right
.
Handles arrays by joining their values with $separator
.
Leading/trailing $left
or $right
characters are trimmed to avoid duplication.
- If
$expression
is an array, its values are concatenated with$separator
. - If
$right
is null, it defaults to the value of$left
. - If
$flag
is false, no wrapping is applied.
Parameters
- $expression : mixed = null
-
The expression to encapsulate (string, array, or any type convertible to string).
- $left : string = ''
-
The left string to prepend.
- $right : string|null = null
-
The right string to append. Defaults to
$left
if null. - $flag : bool = true
-
Whether to apply the wrapping (default: true).
- $separator : string = ' '
-
Separator used when joining array values (default: space).
- $trim : bool = true
-
Whether to trim existing
$left
/$right
characters (default: true).
Tags
Return values
string —The wrapped expression if $flag
is true; otherwise the original expression as string.
betweenBraces()
Encapsulates an expression between braces '{..}'
betweenBraces([mixed $expression = '' ][, bool $useBraces = true ][, string $separator = ' ' ][, bool $trim = true ]) : string
- If the expression is a string, it is wrapped in braces.
- If the expression is an array, its values are concatenated with the given separator, then wrapped in braces.
- If
$useParentheses
is false, the expression is returned without wrapping.
Parameters
- $expression : mixed = ''
-
The expression to wrap.
- $useBraces : bool = true
-
Whether to apply the braces.
- $separator : string = ' '
-
Separator for arrays.
- $trim : bool = true
-
Whether to trim existing
$left
/$right
characters (default: true).
Tags
Return values
string —The wrapped expression.
betweenBrackets()
Encapsulates an expression between brackets '[..]'
betweenBrackets([mixed $expression = '' ][, bool $useBrackets = true ][, string $separator = ' ' ][, bool $trim = true ]) : string
- If the expression is a string, it is wrapped in brackets.
- If the expression is an array, its values are concatenated with the given separator, then wrapped in brackets.
- If
$useParentheses
is false, the expression is returned without wrapping.
Parameters
- $expression : mixed = ''
-
The expression to wrap.
- $useBrackets : bool = true
-
Whether to apply the brackets.
- $separator : string = ' '
-
Separator for arrays.
- $trim : bool = true
-
Whether to trim existing
$left
/$right
characters (default: true).
Tags
Return values
string —The wrapped expression.
betweenDoubleQuotes()
Wraps an expression in double quotes or a custom character.
betweenDoubleQuotes([mixed $expression = '' ][, string $char = '"' ][, bool $useQuotes = true ][, string $separator = ' ' ][, bool $trim = true ]) : string
- Strings are wrapped directly.
- Arrays are concatenated with the given separator, then wrapped.
- Wrapping can be disabled with the
$useQuotes
flag.
Parameters
- $expression : mixed = ''
-
The value to wrap (string, array, or any type convertible to string).
- $char : string = '"'
-
The quote or character to wrap around the expression (default: single quote
'
). - $useQuotes : bool = true
-
Whether to wrap the expression (default: true).
- $separator : string = ' '
-
Separator used to join array elements (default:
' '
). - $trim : bool = true
-
Whether to trim existing
$left
/$right
characters (default: true).
Tags
Return values
string —The resulting wrapped expression.
betweenParentheses()
Encapsulates an expression between parentheses (`()`).
betweenParentheses([mixed $expression = '' ][, bool $useParentheses = true ][, string $separator = ' ' ][, bool $trim = true ]) : string
- If the expression is a string, it is wrapped in parentheses.
- If the expression is an array, its values are concatenated with the given separator, then wrapped in parentheses.
- If
$useParentheses
is false, the expression is returned without wrapping.
Parameters
- $expression : mixed = ''
-
The expression to wrap.
- $useParentheses : bool = true
-
Whether to apply the parentheses.
- $separator : string = ' '
-
Separator for arrays.
- $trim : bool = true
-
Whether to trim existing
$left
/$right
characters (default: true).
Tags
Return values
string —The wrapped expression.
betweenQuotes()
Wraps an expression in quotes or a custom character.
betweenQuotes([mixed $expression = '' ][, string $char = "'" ][, bool $useQuotes = true ][, string $separator = ' ' ][, bool $trim = true ]) : string
- Strings are wrapped directly.
- Arrays are concatenated with the given separator, then wrapped.
- Wrapping can be disabled with the
$useQuotes
flag.
Parameters
- $expression : mixed = ''
-
The value to wrap (string, array, or any type convertible to string).
- $char : string = "'"
-
The quote or character to wrap around the expression (default: single quote
'
). - $useQuotes : bool = true
-
Whether to wrap the expression (default: true).
- $separator : string = ' '
-
Separator used to join array elements (default:
' '
). - $trim : bool = true
-
Whether to trim existing
$left
/$right
characters (default: true).
Tags
Return values
string —The resulting wrapped expression.
betweenSpaces()
Wraps an expression with spaces on both sides.
betweenSpaces([mixed $expression = '' ][, bool $useSpaces = true ][, string $separator = ' ' ][, bool $trim = true ]) : string
Calls between()
with space characters as $left
and $right
. Handles strings, arrays, and optional suppression of spaces.
- String: Simply prepends and appends a space.
- Array: Concatenates array values using the specified
$separator
, then wraps the resulting string in spaces. - Other types: Converted to string before wrapping.
- If
$useSpaces
isfalse
, the expression is returned as-is without any surrounding spaces.
Parameters
- $expression : mixed = ''
-
The value to wrap. Can be string, array, or any type convertible to string.
- $useSpaces : bool = true
-
Whether to apply the surrounding spaces (default:
true
). - $separator : string = ' '
-
Separator to use when
$expression
is an array (default:' '
). - $trim : bool = true
-
Whether to trim existing
$left
/$right
characters (default: true).
Tags
Return values
string —The wrapped expression with spaces if $useSpaces
is true; otherwise the original expression as string.
block()
Format an indented multi-line text block.
block(array<string|int, mixed>|string $input[, string|int $indent = '' ][, string $separator = PHP_EOL ][, bool $keepEmptyLines = true ]) : string
Parameters
- $input : array<string|int, mixed>|string
-
Lines as array or multi-line string.
- $indent : string|int = ''
-
Indentation as string or number of spaces.
- $separator : string = PHP_EOL
-
Line separator (defaults to PHP_EOL).
- $keepEmptyLines : bool = true
-
Whether to preserve empty lines (default: true).
Tags
Return values
string —A single string with the lines joined by $separator and indented.
blockPrefix()
Prefix and indent each line of a multi-line string or array of lines.
blockPrefix(array<string|int, mixed>|string $lines, string $prefix[, string|int $indent = '' ][, string $separator = PHP_EOL ][, bool $keepEmptyLines = true ]) : string
Parameters
- $lines : array<string|int, mixed>|string
-
Array of lines or multi-line string.
- $prefix : string
-
Prefix to apply before each line.
- $indent : string|int = ''
-
Indentation (string or number of spaces).
- $separator : string = PHP_EOL
-
Line separator (default: PHP_EOL).
- $keepEmptyLines : bool = true
-
Whether to keep empty lines (default: true).
Tags
Return values
string —Formatted multi-line string.
blockSuffix()
Suffix and indent each line of a multi-line string or array of lines.
blockSuffix(array<string|int, mixed>|string $lines, string $suffix[, string|int $indent = '' ][, string $separator = PHP_EOL ][, bool $keepEmptyLines = true ]) : string
Parameters
- $lines : array<string|int, mixed>|string
-
Array of lines or multi-line string.
- $suffix : string
-
Suffix to append to each line.
- $indent : string|int = ''
-
Indentation (string or number of spaces).
- $separator : string = PHP_EOL
-
Line separator (default: PHP_EOL).
- $keepEmptyLines : bool = true
-
Whether to keep empty lines (default: true).
Tags
Return values
string —Formatted multi-line string.
camel()
Converts a string to camelCase format.
camel(string|null $source[, array<string|int, mixed> $separators = ["_", "-", "/"] ]) : string
This function transforms the input string by replacing specified separator characters with spaces, capitalizing each word, removing spaces, and then lowercasing the first character.
Parameters
- $source : string|null
-
The input string to convert to camelCase. If null or empty, returns an empty string.
- $separators : array<string|int, mixed> = ["_", "-", "/"]
-
An array of separator characters to be replaced by spaces before conversion. Defaults to ["_", "-", "/"].
Tags
Return values
string —The camelCase representation of the input string.
compile()
Compiles a string, object, boolean, or an array of expressions into a single string.
compile(string|Stringable|array<string|int, mixed>|null $expressions[, string $separator = ' ' ][, callable|null $callback = null ]) : string
Behavior:
- If the input is an array, the values are cleaned with clean() (removing empty or null entries), optionally transformed with a callback, then recursively compiled and concatenated using the specified separator.
- If the input is a string, it is returned as is.
- If the input is an object implementing Stringable, it is cast to string.
- If the input is any other object, it is converted to JSON using json_encode.
- Booleans are converted to
'true'
or'false'
. - Null or unsupported types are converted to an empty string.
Parameters
- $expressions : string|Stringable|array<string|int, mixed>|null
-
The expression(s) to compile.
- $separator : string = ' '
-
The separator used when joining array values (default is a single space).
- $callback : callable|null = null
-
An optional callback applied to each array element before compiling. Signature:
function(mixed $item): mixed
.
Tags
Return values
string —The compiled string expression.
dotKebab()
Converts a camelCase or PascalCase string into a format where the first word is separated by a dot (.) from the rest, which are joined using kebab-case (-).
dotKebab(string|null $source) : string
This is useful for creating structured identifiers or keys that use a namespace-like prefix separated by a dot, followed by a kebab-case suffix.
Internally, this function uses snake() to normalize the input string into lowercase segments separated by a custom delimiter.
Examples:
- "serverAskJwtSecret" → "server.ask-jwt-secret"
- "UserProfilePage" → "user.profile-page"
- "APIKeyManager" → "api.key-manager"
- "foo" → "foo"
- null → ""
Parameters
- $source : string|null
-
The camelCase or PascalCase string to convert.
Tags
Return values
string —The converted string in dot + kebab-case format.
fastFormat()
Quickly formats a string using indexed placeholders and arguments.
fastFormat(string|null $pattern, mixed ...$args) : string
This function replaces indexed tokens like {0}
, {1}
, etc. in a pattern string
with corresponding values from a list of arguments or an array.
- If arguments are passed as a list:
fastFormat("{0} {1}", "hello", "world")
- If passed as a single array:
fastFormat("{0} {1}", ["hello", "world"])
Parameters
- $pattern : string|null
-
The format string containing indexed placeholders.
- $args : mixed
-
The values to insert, either as variadic args or a single array.
Tags
Return values
string —The formatted string with placeholders replaced by values.
format()
Format a template string using an external document.
format(string $template, array<string|int, mixed>|object|string $document[, string $prefix = '{{' ][, string $suffix = '}}' ][, string $separator = '.' ][, string|null $pattern = null ][, bool $preserveMissing = false ]) : string
This function supports different types of documents:
- If the document is a string, it replaces all placeholders with that string.
- If the document is an array or object, it replaces placeholders by key lookup.
Parameters
- $template : string
-
The string to format.
- $document : array<string|int, mixed>|object|string
-
Key-value pairs for placeholders.
- $prefix : string = '{{'
-
Placeholder prefix (default
{{
). - $suffix : string = '}}'
-
Placeholder suffix (default
}}
). - $separator : string = '.'
-
Separator used to traverse nested keys (default
.
). - $pattern : string|null = null
-
Optional full regex pattern to match placeholders (including delimiters).
- $preserveMissing : bool = false
Tags
Return values
string —The formatted string.
formatFromDocument()
Format a template string using key-value pairs from an array or object.
formatFromDocument(string $template, array<string|int, mixed>|object $document[, string $prefix = '{{' ][, string $suffix = '}}' ][, string $separator = '.' ][, string|null $pattern = null ][, bool $preserveMissing = false ]) : string
This function replaces placeholders in the template with corresponding values
found in the provided associative array or object. Placeholders are defined
by a prefix and suffix (default {{
and }}
), and keys can be nested using
the separator (default .
).
Parameters
- $template : string
-
The string to format.
- $document : array<string|int, mixed>|object
-
Key-value pairs for placeholders.
- $prefix : string = '{{'
-
Placeholder prefix (default
{{
). - $suffix : string = '}}'
-
Placeholder suffix (default
}}
). - $separator : string = '.'
-
Separator used to traverse nested keys (default
.
). - $pattern : string|null = null
-
Optional full regex pattern to match placeholders (including delimiters).
- $preserveMissing : bool = false
-
If true, preserves unresolved placeholders instead of removing them (default false).
Tags
Return values
string —The formatted string.
formatQuotedString()
Formats a string value with proper escaping and wrapping using the specified quote style.
formatQuotedString(string $value[, string $quoteStyle = 'single' ][, bool $compact = false ]) : string
This function escapes necessary characters and wraps the string with either single or double quotes, depending on the provided style. Double-quoted strings will have common control characters escaped as well.
Parameters
- $value : string
-
The raw string to quote and escape.
- $quoteStyle : string = 'single'
-
The style of quoting to use: 'single' or 'double'. Default is 'single'.
- $compact : bool = false
Tags
Return values
string —The quoted and escaped string.
formatRequestArgs()
Builds a query string (`?key=value&...`) from an associative array.
formatRequestArgs(array<string|int, mixed> $params[, bool $useNow = false ]) : string
Optionally replaces the value of the from
key with "now"
if $useNow
is set to true
.
This is useful for formatting request parameters in URLs or APIs.
Parameters
- $params : array<string|int, mixed>
-
The associative array of parameters (e.g.,
['from' => 'yesterday', 'limit' => 10]
). - $useNow : bool = false
-
Whether to override the
'from'
key with'now'
if it exists.
Tags
Return values
string —A URL-compatible query string, starting with ?
, or an empty string if $params
is empty.
func()
Generates a function expression like `NAME(arg1,arg2)`.
func(string $name[, mixed $arguments = null ][, string $separator = ',' ]) : string
Parameters
- $name : string
-
The function name.
- $arguments : mixed = null
-
The arguments for the function.
- $separator : string = ','
-
The separator between arguments (default: Char::COMMA).
Tags
Return values
string —The function expression.
hyphenate()
Converts a camelCase or PascalCase string to a hyphenated (kebab-case) string.
hyphenate(string|null $source) : string
This is useful for transforming class names or identifiers into URL- or CSS-friendly format.
Examples:
- "helloWorld" → "hello-world"
- "HTMLParser" → "html-parser"
- "aTestString" → "a-test-string"
Parameters
- $source : string|null
-
The camelCase or PascalCase string to convert.
Tags
Return values
string —The hyphenated (kebab-case) string.
isQuote()
Checks if a character is a known quote character.
isQuote(string $char) : bool
Parameters
- $char : string
Tags
Return values
bool —True if the character is a quote, false otherwise.
isRegexp()
Determines whether a given string is a valid regular expression pattern.
isRegexp(string $pattern) : bool
This function checks if the string can be safely used in a preg_match()
call.
It does not validate semantic correctness (e.g., useless patterns), only syntax.
⚠️ Internally uses the @
operator to suppress warnings from preg_match()
.
Parameters
- $pattern : string
-
The string to test as a potential regex pattern.
Tags
Return values
bool —true
if the string is a valid PCRE regular expression, false
otherwise.
kebab()
Converts a camelCase or PascalCase string into kebab-case (lowercase with hyphens).
kebab(string|null $source) : string
Internally uses the snake()
function with -
as the separator.
Useful for URL slugs, CSS class names, or readable identifiers.
If the input is null
or empty, an empty string is returned.
Parameters
- $source : string|null
-
The input string to transform.
Tags
Return values
string —The kebab-case representation of the input.
key()
Returns a transformed key by optionally prepending a prefix.
key(string $key[, string|null $prefix = '' ][, string $separator = '.' ]) : string
This function allows you to prefix a key string with another string, separated by a custom separator. If the prefix is empty or null, the original key is returned unchanged.
Parameters
- $key : string
-
The key to transform.
- $prefix : string|null = ''
-
Optional prefix to prepend. Default is an empty string.
- $separator : string = '.'
-
The separator to use between the prefix and key. Default is '.'.
Tags
Return values
string —The transformed key. If prefix is provided, returns "prefix{separator}key", otherwise returns the original key.
keyValue()
Build a key-value expression like `key: value`.
keyValue(string|object|int|float|bool $key, mixed $value[, string $separator = ':' ]) : string
This function ensures that both key and value are cast to strings.
Parameters
- $key : string|object|int|float|bool
-
The key (stringable value).
- $value : mixed
-
The value (will be cast to string).
- $separator : string = ':'
-
The separator between key and value (default ':').
Tags
Return values
string —The key-value expression.
latinize()
Converts a string by replacing accented Latin characters with their ASCII equivalents.
latinize([string $source = '' ]) : string
This method transliterates accented characters such as 'é', 'ü', or 'ñ' into their closest ASCII counterparts ('e', 'u', 'n').
Parameters
- $source : string = ''
-
The input string containing accented Latin characters.
Tags
Return values
string —The transliterated string with ASCII characters only.
lower()
Converts a string to lowercase using multibyte-safe methods when possible.
lower(string|null $source) : string
This function ensures proper transformation of characters beyond ASCII, such as accented letters (e.g., 'É' → 'é') or other UTF-8 characters.
If the string is empty or null, an empty string is returned.
Parameters
- $source : string|null
-
The string to convert to lowercase.
Tags
Return values
string —The lowercase version of the string.
luhn()
Validates whether a given string is a valid Luhn code (mod 10 checksum).
luhn(string $number[, bool $lazy = false ]) : bool
The Luhn algorithm is commonly used to validate credit card numbers, IMEI numbers, and other identification codes.
Parameters
- $number : string
-
The input string to validate.
- $lazy : bool = false
-
If true, non-digit characters will be removed before validation. If false, the string must contain only digits.
Tags
Return values
bool —Returns true if the input passes the Luhn check, false otherwise.
object()
Generate a JavaScript-like object string.
object([array<string|int, mixed>|string|null $keyValues = [] ][, bool $useSpace = false ]) : string
This function converts input into a string representing a JavaScript object,
e.g., {name:'Eka',age:48}
. Supported input types:
- Array of key-value pairs:
[ ['key1','value1'], ['key2','value2'] ]
- Associative array:
[ 'key1' => 'value1', 'key2' => 'value2' ]
- Preformatted string:
"key1:'value1',key2:'value2'"
- Null → returns empty braces
}
.
Each array element can be:
- a sub-array with exactly two elements
[key, value]
, - an associative key-value pair,
- or a string already formatted as
key:value
.
Optionally, spaces can be added around braces and after commas with $useSpace
.
Parameters
- $keyValues : array<string|int, mixed>|string|null = []
-
$keyValues Array of pairs, associative array, string, or null
- $useSpace : bool = false
-
Add spaces around braces and after commas
Tags
Return values
string —JavaScript-like object string
pad()
Pads a UTF-8 string to a certain length using a specified padding string and type.
pad(string|null $source, int $size, string $pad, int $type) : string
If the source string is null, it is treated as an empty string. The padding uses grapheme clusters to correctly handle multibyte characters.
Parameters
- $source : string|null
-
The input string or null.
- $size : int
-
Desired length after padding (in grapheme clusters).
- $pad : string
-
The string to use for padding (cannot be empty).
- $type : int
-
One of STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH.
Tags
Return values
string —The padded string.
padBoth()
Pads a UTF-8 string on both sides (left and right) to a certain length using a specified padding string.
padBoth(string|null $source, int $size, string $pad) : string
If the source string is null, it is treated as an empty string. The padding uses grapheme clusters to correctly handle multibyte characters.
Parameters
- $source : string|null
-
The input string or null.
- $size : int
-
Desired length after padding (in grapheme clusters).
- $pad : string
-
The string to use for padding (cannot be empty).
Tags
Return values
string —The string padded on both sides.
padEnd()
Pads a UTF-8 string on the right (end) to a certain length using a specified padding string.
padEnd(string|null $source, int $size, string $pad) : string
If the source string is null, it is treated as an empty string. The padding uses grapheme clusters to correctly handle multibyte characters.
Parameters
- $source : string|null
-
The input string or null.
- $size : int
-
Desired length after padding (in grapheme clusters).
- $pad : string
-
The string to use for padding (cannot be empty).
Tags
Return values
string —The right-padded string.
padStart()
Pads a UTF-8 string on the left (start) to a certain length using a specified padding string.
padStart(string|null $source, int $size, string $pad) : string
If the source string is null, it is treated as an empty string. The padding uses grapheme clusters to correctly handle multibyte characters.
Parameters
- $source : string|null
-
The input string or null.
- $size : int
-
Desired length after padding (in grapheme clusters).
- $pad : string
-
The string to use for padding (cannot be empty).
Tags
Return values
string —The left-padded string.
predicate()
Generate a predicate expression as a string.
predicate(mixed $leftOperand[, string|null $operator = null ][, mixed $rightOperand = null ]) : string
This function builds a simple expression in the form:
leftOperand operator rightOperand
.
If the operator is omitted, only the left operand is returned.
Examples:
predicate('age', '>=', 18); // "age >= 18"
predicate('status', 'is not null'); // "status is not null"
predicate('name'); // "name"
Parameters
- $leftOperand : mixed
-
The left-hand value.
- $operator : string|null = null
-
The operator (optional, e.g., '==', '!=', '>=', 'is null').
- $rightOperand : mixed = null
-
The right-hand value (optional).
Tags
Return values
string —The resulting predicate expression.
predicates()
Generate a complex logical expression with multiple predicates.
predicates(array<string|int, mixed>|null $conditions, string $logicalOperator[, bool $useParentheses = false ][, bool $spacify = true ]) : string|null
Parameters
- $conditions : array<string|int, mixed>|null
-
List of predicate expressions.
- $logicalOperator : string
-
The logical operator to join predicates (e.g., 'AND', 'OR').
- $useParentheses : bool = false
-
Whether to wrap the result in parentheses.
- $spacify : bool = true
Tags
Return values
string|null —The combined expression or null if empty.
prepend()
Prepend one or more prefix strings to the given source string, then normalize the result.
prepend(string|null $source, string ...$prefix) : string
If the source string is null, returns an empty string. If multiple prefixes are provided, they are concatenated before prepending. The resulting string is normalized using Unicode Normalization Form C (NFC).
Parameters
- $source : string|null
-
The original string or null.
- $prefix : string
-
One or more prefix strings to prepend.
Tags
Return values
string —The normalized concatenation of prefix(es) and source.
randomKey()
Generates a random key string, optionally prefixed with a given string and separated by a custom separator.
randomKey(string|null $prefix[, string $separator = '_' ]) : string
The random part is generated using mt_rand()
which provides a pseudo-random integer.
Parameters
- $prefix : string|null
-
Optional prefix to prepend to the key. If null or empty, no prefix is added.
- $separator : string = '_'
-
Separator string between the prefix and the random number. Defaults to underscore '_'.
Tags
Return values
string —The generated random key.
slice()
Extracts a substring from a UTF-8 encoded string using grapheme clusters, which ensures multi-byte characters (like emojis, accented letters) are not broken.
slice(string|null $source[, int $start = 0 ][, int|null $length = null ]) : string
If the source is null, it returns an empty string.
Parameters
- $source : string|null
-
The input string or null.
- $start : int = 0
-
The start position (0-based). Negative values count from the end.
- $length : int|null = null
-
The length of the substring. Defaults to max int (whole string from $start).
Tags
Return values
string —The extracted substring or empty string if $source is null.
snake()
Converts a string to snake_case (or a custom delimiter).
snake(string|null $source[, string $delimiter = '_' ][, string|null $encoding = 'UTF-8' ]) : string
This function transforms camelCase, PascalCase, and space-separated words into snake case or any delimiter specified.
It uses an internal cache (via SnakeCache
) to optimize repeated calls with the same input.
The cache can be flushed by calling SnakeCache::flush()
.
Parameters
- $source : string|null
-
The input string to convert.
- $delimiter : string = '_'
-
The delimiter to use (default is underscore '_').
- $encoding : string|null = 'UTF-8'
-
The encoding parameter is the character encoding. If it is omitted or null, the internal character encoding value will be used.
Tags
Return values
string —The converted snake_case (or custom delimiter) string.
toPhpHumanReadableScalar()
Converts a scalar value (string, boolean, float, etc.) to a simplified, human-readable PHP string representation.
toPhpHumanReadableScalar(mixed $value[, string $quote = 'single' ][, bool $compact = false ]) : string
Useful when a less verbose and more natural output is desired, especially for inline dumps or generated code. Supports custom quote style for strings ('single' or 'double') and optional compact escaping (control characters and trimming).
- Strings are quoted and escaped appropriately using formatQuotedString().
- Booleans are represented as
true
orfalse
. - Floats with no decimal part (e.g., 42.0) are simplified as integers (e.g.,
42
). - Null is represented as
null
. - Other types (e.g. arrays, objects) fall back to
var_export()
representation.
Parameters
- $value : mixed
-
The scalar value to convert.
- $quote : string = 'single'
-
The quote style for strings:
'single'
or'double'
. Default is'single'
. - $compact : bool = false
-
If true, trims and escapes control characters in strings, even with single quotes.
Tags
Return values
string —The human-readable PHP representation of the scalar value.
toPhpString()
Converts any PHP value into a valid PHP code string representation.
toPhpString(mixed $value[, array{compact?: bool, humanReadable?: bool, inline?: bool, indent?: string|int, maxDepth?: int, quote?: "single"|"double", useBrackets?: bool} $options = [] ]) : string
Parameters
- $value : mixed
-
The value to convert.
- $options : array{compact?: bool, humanReadable?: bool, inline?: bool, indent?: string|int, maxDepth?: int, quote?: "single"|"double", useBrackets?: bool} = []
-
Formatting options:
- 'compact' => (bool) Escape control chars even in single-quote (default: false)
- 'humanReadable' => (bool) Human-friendly formatting for scalars (default: false)
- 'inline' => (bool) Single-line output (default: false)
- 'indent' => (string) Indentation string per level (default: ' ')
- 'maxDepth' => (int) Max recursion depth (default: 10)
- 'quote' => ('single'|'double') Quote style for strings (default: 'single')
- 'useBrackets' => (bool) Use brackets for arrays (default: false)
Tags
Return values
string —The PHP code string representing the variable.
convert()
Recursively converts any PHP value into a PHP code string representation.
convert(mixed $value, array<string|int, mixed> $options, int $level, array<string|int, mixed> &$cache) : string
Supports scalars, arrays, objects, and resources with options for formatting, indentation, recursion depth control, and human-readable scalar output. Handles circular references to prevent infinite loops.
Parameters
- $value : mixed
-
The value to convert (scalar, array, object, resource, etc.).
- $options : array<string|int, mixed>
-
Formatting options, including:
- 'maxDepth' (int) Maximum recursion depth allowed.
- 'indent' (string) Indentation string (default 4 spaces).
- 'inline' (bool) Whether to output inline (no line breaks).
- 'useBrackets' (bool) Use short array syntax
[]
instead ofarray()
. - 'quote' (string) Quote style for strings ('single' or 'double').
- 'compact' (bool) Compact output for strings (no extra spaces).
- 'humanReadable' (bool) Whether to use simplified scalar formatting.
- $level : int
-
Current recursion depth level (used internally).
- $cache : array<string|int, mixed>
-
Internal cache to track visited objects/arrays for circular reference detection.
Tags
Return values
string —PHP code string representing the given value.
convertObject()
Converts an object to a PHP string representation with customizable formatting.
convertObject(object $obj, array<string|int, mixed> $options, int $level, array<string|int, mixed> &$cache) : string
Supports detection of circular references to prevent infinite recursion. Handles special cases for DateTimeInterface, backed enums (PHP 8.1+), and Closures. For generic objects, converts public properties recursively with indentation and formatting options.
Parameters
- $obj : object
-
The object to convert.
- $options : array<string|int, mixed>
-
Formatting options including:
- 'maxDepth' (int) Maximum recursion depth allowed.
- 'indent' (string) Indentation string (default 4 spaces).
- 'inline' (bool) Whether to output inline (no line breaks).
- 'useBrackets' (bool) Use short array syntax
[]
instead ofarray()
. - 'quote' (string) Quote style for strings ('single' or 'double').
- 'compact' (bool) Compact output for strings (no extra spaces).
- $level : int
-
Current recursion depth level.
- $cache : array<string|int, mixed>
-
Internal cache to track visited objects for circular reference detection.
Tags
Return values
string —PHP code string representing the object.
convertArray()
Converts an associative or sequential PHP array into a human-readable PHP string representation.
convertArray(array<string|int, mixed> $array, array<string|int, mixed> $options, int $level, array<string|int, mixed> &$cache) : string
This function is typically used as part of a recursive serialization process to represent array structures
in a PHP-style syntax. It supports pretty-printing, inline formatting, bracketed or classic array()
syntax,
and limits recursion via the maxDepth
option.
The output is intended for debugging, code generation, or inspection tools.
Parameters
- $array : array<string|int, mixed>
-
The array to convert.
- $options : array<string|int, mixed>
-
An associative array of formatting options:
- 'indent' (string): The indentation string (e.g.,
' '
). - 'inline' (bool): If true, output the array on a single line.
- 'useBrackets' (bool): If true, use
[]
instead ofarray()
. - 'maxDepth' (int): The maximum recursion depth.
- 'indent' (string): The indentation string (e.g.,
- $level : int
-
The current depth level in the recursion (used for indentation).
- $cache : array<string|int, mixed>
-
A reference to a cache array used for detecting circular references.
Tags
Return values
string —The PHP-like string representation of the array.
toString()
Converts a value to a string representation.
toString(mixed $value) : string
- Returns an empty string for
null
values. - Preserves the sign of
-0.0
as the string "-0". - Converts arrays recursively by flattening and joining with commas.
- Accepts objects implementing
Stringable
.
Parameters
- $value : mixed
-
The value to convert.
Tags
Return values
string —The string representation of the value.
urlencode()
Encodes the specified URI according to RFC 3986.
urlencode(string $uri) : string
This function applies PHP's built-in urlencode() and then decodes certain reserved characters back to their literal forms, matching RFC 3986 requirements.
Parameters
- $uri : string
-
The URI string to encode.
Tags
Return values
string —The RFC 3986 compliant encoded URI string.
wrap()
Wrap a string with a given character.
wrap(string $value[, string $char = '`' ]) : string
Parameters
- $value : string
-
The value to wrap.
- $char : string = '`'
-
The character to wrap with.
Tags
Return values
string —The wrapped value.
wrapBlock()
Wraps a block of lines with a header and footer line.
wrapBlock(array<string|int, mixed>|string $lines, string $before, string $after[, string|int $indent = '' ][, string $separator = PHP_EOL ][, bool $keepEmptyLines = true ]) : string
Parameters
- $lines : array<string|int, mixed>|string
-
Array or string of lines to wrap.
- $before : string
-
Line inserted before the block.
- $after : string
-
Line inserted after the block.
- $indent : string|int = ''
-
Indentation for the inner block (default: '').
- $separator : string = PHP_EOL
-
Line separator (defaults to PHP_EOL).
- $keepEmptyLines : bool = true
-
Whether to preserve empty lines (default: true).
Tags
Return values
string —Final wrapped block.