Oihana PHP

strings

Table of Contents

Namespaces

helpers

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
throws
InvalidArgumentException

If the resulting string is invalid UTF-8 or cannot be normalized.

example
use function oihana\core\strings\append;

echo append( 'hello', ' ', 'world'); // Outputs: "hello world"
echo append( null, 'foo');           // Outputs: "foo"
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
author

Marc Alcaraz

since
1.0.6
example
echo between('x', '<', '>');          // '<x>'
echo between(['a', 'b'], '[', ']');  // '[a b]'
echo between('y', '"', null, false); // 'y'
echo between('[test]', '[', ']');    // '[test]' (trims duplicate brackets)
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
example
betweenBraces('id: 1');           // '{ id: 1 }'
betweenBraces(['x', 'y']);        // '{ x y }'
betweenBraces(['x', 'y'], false); // 'x y'
author

Marc Alcaraz

since
1.0.6
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
example
betweenBrackets( [ 'a' , 'b' ] ) ;     // '[a b]'
betweenBrackets( 'index: 3' ) ;       // '[index: 3]'
betweenBrackets( 'value' , false ) ;  // 'value'
author

Marc Alcaraz

since
1.0.6
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
example
betweenQuotes('world');        // returns "world"
betweenQuotes(['foo', 'bar']); // returns "foo bar"
since
1.0.6
author

Marc Alcaraz

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
example
betweenParentheses( 'sum: 10' ) ;       // '(sum: 10)'
betweenParentheses( ['a', 'b', 'c'] ) ; // '(a b c)'
betweenParentheses( 'val', false ) ;   // 'val'
author

Marc Alcaraz

since
1.0.6
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
example
betweenQuotes('world');               // returns "'world'"
betweenQuotes(['foo', 'bar']);        // returns "'foo bar'"
betweenQuotes('data', '`');           // returns '`data`'
betweenQuotes('raw', "'", false);     // returns 'raw'
betweenQuotes(['a','b'], '"', true, ','); // returns '"a,b"'
since
1.0.6
author

Marc Alcaraz

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 is false, 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
example
betweenSpaces('hello');                    // returns ' hello '
betweenSpaces('hello', false);             // returns 'hello'
betweenSpaces(['a', 'b', 'c']);            // returns ' a b c '
betweenSpaces(['a', 'b', 'c'], true, ','); // returns ' a,b,c '
betweenSpaces(123);                        // returns ' 123 '
author

Marc Alcaraz

since
1.0.6
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
example

Use an input array :

echo block
([
    'if ($host ~* ^example\\.com$)',
    '{',
    '    rewrite ^(.*) https://www.example.com$1 permanent;',
    '    break',
    '}'
] , 4 ) ;

echo block(['a', 'b', 'c'], '-', 0); // "a-b-c"

Use an input string:

echo blockLines( "foo\nbar", '-> ' ) ;
// Output:
// -> foo
// -> bar
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
echo blockPrefix("a\n\nb", "// ", 2);
// Output:
//   // a
//   //
//   // b

echo blockPrefix(['a', '', 'b'], '-> ', '|');
// Output: -> a|-> |-> b

echo blockPrefix('', '>>>');
// Output: >>>
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
echo blockSuffix("a\n\nb", " //", 2);
// Output:
//   a //
//   //
//   b //

echo blockSuffix(['a', '', 'b'], ' <-', '|');
// Output: a <-| <-|b <-

echo blockSuffix('', '<<<');
// Output: <<<
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
echo camel('hello_world');        // Outputs: helloWorld
echo camel('foo-bar_baz');        // Outputs: fooBarBaz
echo camel('user/name');          // Outputs: userName
echo camel('alreadyCamelCase');   // Outputs: alreadyCamelCase
echo camel(null);                 // Outputs: (empty string)
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
author

Marc Alcaraz

since
1.0.0
example
use function oihana\core\expressions\compile;

echo compile( [ 'foo' , '' , 'bar' ] )        . PHP_EOL; // 'foo bar'
echo compile( [ 'a'   , null , 'c' ] , ', ' ) . PHP_EOL; // 'a, c'
echo compile( 'baz' )                         . PHP_EOL; // 'baz'
echo compile( null )                          . PHP_EOL; // ''
echo compile([1, 2, 3], '-', fn($v) => $v*2)  . PHP_EOL; // '2-4-6'
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
example
echo dotKebab("serverAskJwtSecret");
// Output: "server.ask-jwt-secret"

echo dotKebab("UserProfilePage");
// Output: "user.profile-page"

echo dotKebab("APIKeyManager");
// Output: "api.key-manager"

echo dotKebab("foo");
// Output: "foo"

echo dotKebab(null);
// Output: ""
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
echo fastFormat("Hello {0}", "World");
// Output: "Hello World"

echo fastFormat("Coordinates: {0}, {1}", [45.0, -73.0]);
// Output: "Coordinates: 45, -73"

echo fastFormat("User {0} has {1} points", "Alice", 1500);
// Output: "User Alice has 1500 points"

echo fastFormat("Missing: {0}, {1}", "only one");
// Output: "Missing: only one, {1}" (missing index stays unchanged)

class Person {
    public function __toString(): string {
        return "John Doe";
    }
}
echo fastFormat("Name: {0}", new Person());
// Output: "Name: John Doe"
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
author

Marc Alcaraz (ekameleon)

since
1.0.0
example
use function oihana\core\strings\format;

// Using an array document
echo format('Hello, {{name}}!', ['name' => 'Alice']);
// Output: 'Hello, Alice!'

// Using nested keys with separator
echo format('ZIP: {{user.address.zip}}',
[
   'user' => ['address' => ['zip' => '75000']]
]);
// Output: 'ZIP: 75000'

// Using a custom prefix and suffix
echo format( 'Today is [[day]]' , ['day' => 'Monday'] , '[[' , ']]' ) ;
// Output: 'Today is Monday'

// Using a full custom regex pattern
$template = 'Hello, <<name>>!' ;
$doc      = ['name' => 'Alice'] ;
$pattern  = '/<<(.+?)>>/' ;
echo format($template, $doc, '<<', '>>', '.', $pattern);
// Output: 'Hello, Alice!'

// Using a string document: all placeholders replaced by same string
echo format( 'User: {{name}}, Role: {{role}}', 'anonymous');
// Ou
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
author

Marc Alcaraz (ekameleon)

since
1.0.0
example
use function oihana\core\strings\formatFromDocument;

echo formatFromDocument('Hello, {{name}}!', ['name' => 'Alice']);
// Output: 'Hello, Alice!'

echo formatFromDocument('Today is [[day]]', ['day' => 'Monday'], '[[', ']]');
// Output: 'Today is Monday'

echo formatFromDocument('ZIP: {{user.address.zip}}', [
    'user' => ['address' => ['zip' => '75000']]
]);
// Output: 'ZIP: 75000'

Custom pattern example

$template = 'Hello, <<name>>!';
$doc = ['name' => 'Alice'];
$pattern = '/<<(.+?)>>/';
echo formatFromDocument($template, $doc, '<<', '>>', '.', $pattern);
// Output: 'Hello, Alice!'

Preserve unresolved placeholder

echo formatFromDocument
(
    'Hello, {{name}}! From {{country}}.',
    ['name' => 'Alice'] ,
    preserveMissiong: true
) ;
// Output: 'Hello, Alice! From {{country}}.'
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
example
echo formatQuotedString("Hello world");                    // 'Hello world'
echo formatQuotedString("Line\nBreak", 'double');         // "Line\nBreak"
echo formatQuotedString("She said: 'hi'");                // 'She said: \'hi\''
echo formatQuotedString("Use \\ backslash", 'double');    // "Use \\ backslash"
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
echo formatRequestArgs(['from' => '2023-01-01', 'limit' => 10]);
// Output: "?from=2023-01-01&limit=10"

echo formatRequestArgs(['from' => 'yesterday', 'limit' => 5], true);
// Output: "?from=now&limit=5"

echo formatRequestArgs([]);
// Output: ""

echo formatRequestArgs(['search' => 'php functions', 'page' => 2]);
// Output: "?search=php functions&page=2"
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
func('CALL', ['a', 'b']); // 'CALL(a,b)'
author

Marc Alcaraz

since
1.0.0
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
example
echo hyphenate("helloWorld");
// Output: "hello-world"

echo hyphenate("SimpleXMLParser");
// Output: "simple-xml-parser"

echo hyphenate("AString");
// Output: "a-string"

echo hyphenate(null);
// Output: ""
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
author

Marc Alcaraz

since
1.0.0
example
isQuote('"');  // true
isQuote('`');  // true
isQuote('a');  // false
isQuote('»');  // true
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
example
isRegexp('/^[a-z]+$/');       // true
isRegexp('/[0-9]{3,}/');      // true
isRegexp('not a regex');      // false (missing delimiters)
isRegexp('/unterminated');    // false
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
echo kebab("helloWorld");      // Outputs: "hello-world"
echo kebab("HelloWorld");      // Outputs: "hello-world"
echo kebab("XMLHttpRequest");  // Outputs: "xml-http-request"
echo kebab(null);              // Outputs: ""
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
use function oihana\core\strings\key;

key('name');                  // Returns 'name'
key('name', 'doc');           // Returns 'doc.name'
key('name', 'doc', '::');     // Returns 'doc::name'
key('name', 'doc', '->');     // Returns 'doc->name'
key('name', '');              // Returns 'name'
key('name', null);            // Returns 'name'
author

Marc Alcaraz

since
1.0.0
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
example
echo keyValue( 'name' , 'Eka' );        // 'name:Eka'
echo keyValue( 'age' , 30, ' = ' );     // 'age=30'
echo keyValue( 'active' , true );       // 'active:true'
echo keyValue( 'tags' , ['php','js'] ); // 'tags:[php, js]'
echo keyValue( 'description' , null );  // 'description:null'
author

Marc Alcaraz

since
1.0.0
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
example
echo latinize('Café Münsterländer'); // Outputs: Cafe Munsterlander
echo latinize('¡Hola señor!');      // Outputs: ¡Hola senor!
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
echo lower("HELLO WORLD");
// Output: "hello world"

echo lower("École Française");
// Output: "école française"

echo lower(null);
// Output: ""

echo lower("123-ABC");
// Output: "123-abc"
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
echo luhn("79927398713");           // Outputs: true (valid Luhn)
echo luhn("7992 7398 713", true);   // Outputs: true (valid Luhn, spaces removed)
echo luhn("1234");                  // Outputs: false (invalid Luhn)
author

Marc Alcaraz (ekameleon)

since
1.0.0
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:

  1. Array of key-value pairs: [ ['key1','value1'], ['key2','value2'] ]
  2. Associative array: [ 'key1' => 'value1', 'key2' => 'value2' ]
  3. Preformatted string: "key1:'value1',key2:'value2'"
  4. 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
throws
InvalidArgumentException

If an array element is invalid or the type is unsupported

example
echo object([['name', "'Eka'"], ['age', 47]]);
// Outputs: "{name:'Eka',age:47}"

echo object([['name', "'Eka'"], ['age', 47]], true);
// Outputs: "{ name:'Eka', age:47 }"

echo object(['name' => "'Eka'", 'age' => 47]);
// Outputs: "{name:'Eka',age:47}"

echo object("foo:'bar',baz:42");
// Outputs: "{foo:'bar',baz:42}"

echo object(null, true);
// Outputs: "}"
since
1.0.0
author

Marc Alcaraz

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
throws
InvalidArgumentException

If the padding type is invalid or $pad is empty.

example
use function oihana\core\strings\pad;

echo pad('hello', 10, ' ', STR_PAD_RIGHT); // Outputs: "hello     "
echo pad('hello', 10, '☺', STR_PAD_LEFT);  // Outputs: "☺☺☺☺☺hello"
echo pad('hello', 10, 'ab', STR_PAD_BOTH); // Outputs: "ababahelloaba"
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
throws
InvalidArgumentException

If the padding string is empty or invalid UTF-8.

example
use function oihana\core\strings\padBoth;

echo padBoth('hello', 11, 'ab');    // Outputs: "abhelloabab"
echo padBoth(null, 6, '*');         // Outputs: "******"
echo padBoth('test', 10, '☺');      // Outputs: "☺☺☺test☺☺☺"
echo padBoth('emoji', 9, '🚀');     // Outputs: "🚀🚀emoji🚀"
echo padBoth('pad', 3, '-');        // Outputs: "pad" (size <= string length, no padding)
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
throws
InvalidArgumentException

If the padding string is empty or invalid UTF-8.

example
use function oihana\core\strings\padEnd;

echo padEnd('hello', 10, '☺');  // Outputs: "hello☺☺☺☺☺"
echo padEnd(null, 5, '*');      // Outputs: "*****"
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
throws
InvalidArgumentException

If the padding string is empty or invalid UTF-8.

example
use function oihana\core\strings\padStart;

echo padStart('hello', 10, '☺');  // Outputs: "☺☺☺☺☺hello"
echo padStart(null, 5, '*');      // Outputs: "*****"
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
since
1.0.0
author

Marc Alcaraz

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
example
$predicates = [
    $this->predicate('a', '==', 1),
    $this->predicate('b', '>', 5)
];
$this->predicates( $predicates , 'AND' , true ) ; // '(a == 1 AND b > 5)'
since
1.0.0
author

Marc Alcaraz

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
throws
InvalidArgumentException

If the resulting string is invalid UTF-8 or cannot be normalized.

example
use function oihana\core\strings\prepend;

echo prepend( 'world', 'hello', ' ' ); // Outputs: "hello world"
echo prepend( null, 'foo');             // Outputs: "foo"
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
echo randomKey("user");       // Possible output: "user_123456789"
echo randomKey(null);         // Possible output: "987654321"
echo randomKey("order", "-"); // Possible output: "order-456789123"
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
use function oihana\core\strings\slice;

echo slice ( "Hello World", 6 ) ; // Outputs: "World"

echo slice ( "👩‍👩‍👧‍👧 family", 0, 5 ) ; // Outputs: "👩‍👩‍👧‍👧"

echo slice ( null ) ; // Outputs: ""

echo slice ( "Hello" , -3 , 2 ) ; // Outputs: "ll"
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example

Basic usage

echo snake("helloWorld");  // Outputs: "hello_world"
echo snake("HelloWorld");  // Outputs: "hello_world"
echo snake("Hello World"); // Outputs: "hello_world"
echo snake("helloworld");  // Outputs: "helloworld"

With numbers

echo snake("helloWorld123"); // Outputs: "hello_world123"
echo snake("UserID42");      // Outputs: "user_id_42"

Unicode support

echo snake("helloWorldCafé"); // Outputs: "hello_world_café"
echo snake("CaféAuLait");     // Outputs: "café_au_lait"
echo snake("NaïveBayesian");  // Outputs: "naïve_bayesian"
echo snake("Emoji😊Test");    // Outputs: "emoji_😊_test"

Complex cases

echo snake("MyXMLParser");  // Outputs: "my_xml_parser"
echo snake("JSONToArray");  // Outputs: "json_to_array"
echo snake("hello world how are you"); // Outputs: "hello_world_how_are_you"

Custom delimiters

echo snake("helloWorld", "-"); // Outputs: "hello-world"
echo snake("helloWorld", "|"); // Outputs: "hello|world"
echo snake("helloWorld", " "); // Outputs: "hello world"

Edge cases

echo snake("");   // Outputs: ""
echo snake(null); // Outputs: ""

Clear the internal cache if needed

use oihana\core\strings\helpers\SnakeCache;
SnakeCache::flush();
author

Marc Alcaraz (ekameleon)

since
1.0.0
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 or false.
  • 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
example
echo toPhpHumanReadableScalar("hello");                        // 'hello'
echo toPhpHumanReadableScalar("He said: \"ok\"", 'double');   // "He said: \"ok\""
echo toPhpHumanReadableScalar(true);                          // true
echo toPhpHumanReadableScalar(false);                         // false
echo toPhpHumanReadableScalar(42.0);                          // 42
echo toPhpHumanReadableScalar(3.14);                          // 3.14
echo toPhpHumanReadableScalar(null);                          // null
echo toPhpHumanReadableScalar("Line\nBreak", 'single');       // 'Line
                                                            // Break'
echo toPhpHumanReadableScalar("Line\nBreak", 'single', true); // 'Line\nBreak'
see
formatQuotedString()
since
1.0.0
author

Marc Alcaraz

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
example

Example 1: Basic scalar values

echo toPhpString(42);       // '42'
echo toPhpString('hello'); // '\'hello\''
echo toPhpString(true);    // 'true'
echo toPhpString(null);    // 'null'

Example 2: Flat array with short syntax

echo toPhpString(['a' => 1, 'b' => 2], ['useBrackets' => true]);
// Output: ['a' => 1, 'b' => 2]

Example 3: Nested object and array, inline

$data =
[
    'user' =>
    [
        'name' => 'Alice',
        'roles' => ['admin', 'editor'],
        'profile' => (object)['active' => true, 'age' => 30]
    ]
];
echo toPhpString($data, ['useBrackets' => true]);
// Output: ['user' => ['name' => 'Alice', 'roles' => ['admin', 'editor'], 'profile' => (object)['active' => true, 'age' => 30]]]

Example 4: Multiline formatted with indentation

echo toPhpString( $data ,
[
    'useBrackets' => true,
    'inline' => false,
    'indent' => 2
]);
// Output:
// [
//   'user' => [
//     'name' => 'Alice',
//     'roles' => [
//       'admin',
//       'editor'
//     ],
//     'profile' => (object)[
//       'active' => true,
//       'age' => 30
//     ]
//   ]
// ]

Example 5: Object with closure and max depth

$obj = new stdClass();
$obj->callback = fn() => null;
$obj->deep = ['level1' => ['level2' => ['level3' => ['level4' => $obj]]]];

echo toPhpString($obj, ['maxDepth' => 3, 'useBrackets' => true]);
// Output includes: '<max-depth-reached>', '<closure>'

### Example 6: Use double quotes and a human readable rendering
```php
$data =
[
   'message' => "Hello\nWorld",
   'count'   => 1.0,
   'active'  => true
];

echo toPhpString( $data,
[
   'useBrackets'   => true,
   'humanReadable' => true,
   'quote'         => 'double'
]);

// Output
// [
//     'message' => "Hello\nWorld",
//     'count'   => 1,
//     'active'  => true
// ]
author

Marc Alcaraz (ekameleon)

since
1.0.0
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 of array().
  • '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
example
$data = [
    'name' => "Oihana",
    'count' => 42,
    'active' => true,
    'nested' => ['a', 'b', 'c']
];

echo convert($data, ['maxDepth' => 3, 'indent' => '  ', 'inline' => false, 'useBrackets' => true, 'quote' => 'single', 'compact' => false, 'humanReadable' => true], 0, []);

// Output:
// [
//   'name' => 'Oihana',
//   'count' => 42,
//   'active' => true,
//   'nested' => [
//     'a',
//     'b',
//     'c',
//   ],
// ]
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 of array().
  • '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
example
$dt = new DateTimeImmutable('2023-08-04T10:30:00+00:00');
echo convertObject($dt, ['maxDepth' => 3, 'indent' => '  ', 'inline' => false, 'useBrackets' => true, 'quote' => 'single', 'compact' => false], 0, []);

// Output:
// new \DateTimeImmutable('2023-08-04T10:30:00+00:00')
since
1.0.0
author

Marc Alcaraz

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 of array().
  • 'maxDepth' (int): The maximum recursion depth.
$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
example
$array = [
    'name' => 'Alice',
    'age'  => 30,
    'tags' => ['developer', 'php'],
];

echo convertArray( $array ,
[
    'indent'      => '  ',
    'inline'      => false,
    'useBrackets' => true,
    'maxDepth'    => 3,
], 0, $cache = []);

// Output:
// [
//   'name' => 'Alice',
//   'age' => 30,
//   'tags' => [
//     'developer',
//     'php'
//   ]
// ]
see
convert()

For the recursive value conversion used within this function.

since
1.0.0
since
1.0.0
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
example
echo toString(null);        // Outputs: ""
echo toString("hello");     // Outputs: "hello"
echo toString(123);         // Outputs: "123"
echo toString(-0.0);        // Outputs: "-0"
echo toString([1, 2, 3]);   // Outputs: "1,2,3"
echo toString([[1, 2], 3]); // Outputs: "1,2,3"

With Stringable object:

class Foo implements Stringable
{
    public function __toString() { return "foo"; }
}
echo toString(new Foo()); // Outputs: "foo"
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
echo urlencode("https://example.com/foo?bar=baz&qux=1");
// Outputs: https%3A%2F%2Fexample.com%2Ffoo%3Fbar%3Dbaz%26qux%3D1

echo urlencode("hello world!");
// Outputs: hello%20world!
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
echo wrap('column'); // `column`
echo wrap('`column`'); // `\`column\``
echo wrap('column', '"'); // "column"
author

Marc Alcaraz (ekameleon)

since
1.0.0
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
example
echo wrapBlock("line1\nline2", '{', '}', 4);
// Output:
// {
//     line1
//     line2
// }
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string

Final wrapped block.


        
On this page

Search results