Oihana PHP

strings

Table of Contents

Namespaces

helpers

Functions

camel()  : string
Converts a string to camelCase format.
fastFormat()  : string
Quickly formats a string using indexed placeholders and arguments.
formatRequestArgs()  : string
Builds a query string (`?key=value&...`) from an associative array.
hyphenate()  : string
Converts a camelCase or PascalCase string to a hyphenated (kebab-case) string.
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).
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).
randomKey()  : string
Generates a random key string, optionally prefixed with a given string and separated by a custom separator.
snake()  : string
Converts a string to snake_case (or a custom delimiter).
toString()  : string
Converts a value to a string representation.
urlencode()  : string
Encodes the specified URI according to RFC 3986.

Functions

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.

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.

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.

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.

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.

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.

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.

snake()

Converts a string to snake_case (or a custom delimiter).

snake(string|null $source[, string $delimiter = '_' ]) : 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 '_').

Tags
example
echo snake("helloWorld");     // Outputs: "hello_world"
echo snake("HelloWorld");     // Outputs: "hello_world"
echo snake("Hello World");    // Outputs: "hello_world"
echo snake("helloWorld", "-"); // Outputs: "hello-world"

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.

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.


        
On this page

Search results