Luminova Framework

PHP Luminova: PHP String Object Helper Class

Last updated: 2026-11-28 20:57:12

An object-oriented, string object utility class for PHP. It simplifies string manipulation with built-in methods for casing, trimming, masking, pattern matching, slug generation, and prototype.

The Str class offers a fluent, object-oriented interface for string manipulation in PHP.It combines readability, power, and flexibility, making it easy to perform common string operations without breaking flow or readability.

You can transform, compare, extract, mask, or hash strings, all through chainable methods.In addition, Str implements the PrototypeableInterface, allowing you to dynamically add new methods or properties at runtime, similar to JavaScript’s prototype model.


Key Features

  • Fluent API – Most methods are chainable for cleaner code.
  • Safe and predictable – Avoids mutating the original string unless explicitly set.
  • Prototypeable – Extend the class at runtime with your own methods or properties.
  • Utility-rich – Includes case conversions, trimming, masking, formatting, and more.
  • Object-friendly – Implements PHP’s Stringable interface.

Usage

The Str class provides an object-oriented way to work with strings in Luminova Application.It makes string manipulation cleaner and more expressive.

Creating a String Object

You can create a new Str instance in two ways, directly using the constructor or the of() static helper method.

use Luminova\Components\String\Str;

// Using constructor
$str = new Str('Hello World');

// Using static helper
$str = Str::of('Hello World');

Both examples initialize a string object that you can manipulate with class methods.


Optional Array Access

The Str object allows you to access characters by index, just like an array.

$str = Str::of('Hello');

// Access single characters by 0-based index
echo $str[1];  // Outputs: "e"
echo $str[3];  // Outputs: "l"

// Out-of-range indexes return an empty string
echo $str[10]; // Outputs: ""

Note:This works best with plain ASCII strings. For multibyte characters (like emojis or non-latin scripts), consider using at() for safe Unicode support.


Transforming Strings

Once you have an instance, you can perform various transformations easily:

echo $str->toUpperCase();       // "HELLO WORLD"
echo $str->slugify();           // "hello-world"
echo $str->between('He', 'ld'); // "llo Wor"
echo $str->repeat(2);           // "Hello WorldHello World"

Each method returns a new Str object (unless otherwise noted), allowing method chaining.

Example:

echo Str::of('  Hello World  ')
    ->trim()
    ->slugify()
    ->toUpperCase(); // "HELLO-WORLD"

Extending with Prototype Methods

You can extend the Str class at runtime using prototype methods.This allows you to dynamically add new methods or utilities without modifying the class itself.

// Add a dynamic method
$str->prototype('greet', fn($name) => "{$this->valueOf}, {$name}!");
echo $str->greet('Peter'); // "Hello World, Peter!"

You can also add new utilities:

$str->prototype('toArray', fn() => explode(' ', $this->valueOf));
print_r($str->toArray()); // ["Hello", "World"]

Note:Inside a prototype function, use $this->valueOf to access the string value.The $valueOf property is protected and cannot be accessed outside the class scope.


Class Definition

This class implements Luminova PrototypeableInterface, allowing you to dynamically add methods at runtime.


Properties

valueOf

The internal property holding the string value.

protected string $valueOf = '';

Encoding Property

Optional string encoding (default: auto detect or fallback to UTF-8).

protected ?string $encoding = null;

encodings

Auto encoding detection order.

/**
 * @var array<int, string>
 */
protected static array $encodings = [
    'UTF-8',
    'UTF-16',
    'UTF-32',
    'ISO-8859-1',
    'ISO-8859-15',
    'WINDOWS-1252',
    'LATIN1',
    'ASCII',
    'SJIS',
    'EUC-JP',
    'CP850',
    'BIG5'
];

Methods

constructor

Create a new string object.

public function __construct(
    string $valueOf = '',
    ?string $encoding = null
)

Parameters:

ParameterTypeDescription
$valueOfstringThe initial string value (default '').
$encoding?stringOptional string encoding (default: auto detect or fallback to UTF-8).

Example:

$str = new Str('Hello');

of

Create a new Str instance from a string or any Stringable value.

This static factory method makes it easy to initialize the string object without using the new keyword directly.

public static function of(Stringable|string $valueOf, ?string $encoding = null): self

Parameters:

ParameterTypeDescription
$valueOfStringable&#124;stringThe string or Stringable object to wrap.
$encoding?stringOptional string encoding (default: auto detect or fallback to UTF-8).

Return:

self - Returns a new Str instance containing the given value.

Example:

$str = Str::of('Hello World');

// From Object that implements Stringable
$str = Str::of(new SomeStringObject(
    'From Another Stringable Class Object'
));

fromCharCode

Create a string from one or more Unicode values.

public static function fromCharCode(int ...$codes): self

Parameters:

ParameterTypeDescription
$codesintArguments of unicode code points.

Return:

self - Returns a new Str instance representing the characters.

Example:

$str = Str::fromCharCode(72, 101, 108, 108, 111);

echo $str; // "Hello"

fromCodePoint

Create a string from Unicode code points (like String.fromCodePoint).

public static function fromCodePoint(int ...$points): self

Parameters:

ParameterTypeDescription
$pointsintArguments of unicode code points.

Return:

self - Returns a new Str instance representing the characters.

Example:

$str = Str::fromCodePoint(9731, 9733, 9842);

echo $str; // "☃★♲"

value

Set or update the current string value.

public function value(Stringable|string $value, ?string $encoding = null): self

Parameters:

ParameterTypeDescription
$valueStringable&#124;stringThe new string value.
$encoding?stringOptional string encoding (default: auto detect or fallback to UTF-8).

Return:

self - Returns the same instance for chaining.

Example:

$str = new Str('Old value');

echo $str; // Old Value

// Update with a new value
$str->value('New value');

echo $str; // New Value

at

Get the character at the specified position.

Supports multibyte characters and negative indexes, where -1 represents the last character.Returns an empty string if the index is out of range.

public function at(int $index): self

Parameters:

ParameterTypeDescription
$indexintThe zero-based character position (can be negative).

Return:

self - Returns a new Str instance containing the character, or an empty instance if not found.

Example:

echo Str::of('Hello')->at(1);   // "e"
echo Str::of('Hello')->at(-1);  // "o"
echo Str::of('你好')->at(1);    // "好"
echo Str::of('Hello')->at(99);  // ""

hash

Hash the string using the given algorithm.

public function hash(string $algo = 'xxh3', bool $binary = false, array $options = []): self

Parameters:

ParameterTypeDescription
$algostringThe hash algorithm (e.g., md5, sha256) (default 'xxh3').
$binaryboolIf true, outputs raw binary data instead of hex (default false).
$optionsarray<array-key,mixed>Optional hashing options.

Return:

self - Returns the same instance with the hashed value.

Note:This modifies the original string value.

Throws:

Example:

echo Str::of('Some Secrete Message')
    ->hash('sha256')
    ->toString();

length

Calculate length of the string value.

public function length(?string $encoding = null): int

Parameters:

ParameterTypeDescription
$encoding?stringCharacter encoding for multibyte support.

Return:

int - Returns the number of characters in the string.

Example:

echo Str::of('Hello')->length(); // 5

encoding

Detect the character encoding of the current string.

This method uses mb_detect_encoding() to guess the encoding from a list of common encodings.If detection fails, it returns the $default value.

If $strict is true, mb_detect_encoding will only return a valid encoding if it can verify that the string is valid in that encoding.

public function encoding(bool $strict = true, string $default = 'UTF-8'): string

Parameters:

ParameterTypeDescription
$strictboolWhether to use strict mode for detection (default: true).
$defaultstringThe fallback encoding to return if detection fails (default: UTF-8).

Return:

string - Return the detected or default encoding name.

Example:

Str::of("Hello")->encoding();
// 'UTF-8'

Str::of(iconv('UTF-8', 'ISO-8859-1', "Olá"))->encoding();
// 'ISO-8859-1'

split

Split the string into chunks of the specified length.

This converts the string value into an array of $length characters.

public function split(int $length = 1): array

Parameters:

ParameterTypeDescription
$lengthintThe length of each chunk.

Return:

string[] - An array of string segments.

Example:

$str = new Str('abcde');

print_r($str->split(2));
// Array("ab", "cd", "e")

replace

Replace occurrences of a string or array of strings.

This method uses PHP str_replace to replace one or more occurrence.

public function replace(string|array $search, string|array $replacement): self

Parameters:

ParameterTypeDescription
$searchstring&#124;array<array-key,mixed>The string or array to search for.
$replacementstring&#124;array<array-key,mixed>The replacement string or array.

Return:

self - Returns a new Str instance with replacements applied.

Example:

echo Str::of('Hello World')->replace('World', 'PHP');
// "Hello PHP"

echo Str::of('I like cats and cats')->replace('cats', 'dogs');
// "I like dogs and dogs"

replaceAll

Replace occurrences using a regular expression.

This method uses uses regex to find and replace all occurrence.

public function replaceAll(string|array $pattern, string|array $replacement): self

Parameters:

ParameterTypeDescription
$patternstring&#124;array<array-key,mixed>A regular expression pattern or array of patterns.
$replacementstring&#124;array<array-key,mixed>The replacement string or array.

Return:

self - Returns a new Str instance with replacements applied.

Example:

echo Str::of('Hello World')->replaceAll('/World/i', 'PHP');
// "Hello PHP"

echo Str::of('I like cats and Cats')->replaceAll('/cats/i', 'dogs');
// "I like dogs and dogs"

repeat

Repeat the string a given number of times.

It also support an optional suffix separator for the repeat process.

public function repeat(int $times, string $separator = ''): self

Parameters:

ParameterTypeDescription
$timesintThe number of repetitions.
$separatorstringAn optional repeat suffix separator.

Return:

self - Returns a new instance with the repeated string.

Example:

$str = new Str('Hi');

echo $str->repeat(3);
// HiHiHi

echo $str->repeat(3, '-');
// Hi-Hi-Hi

pad

Pad the string to a new length using a given character.

public function pad(int $length, string $char = " ", string $type = 'right'): self

Parameters:

ParameterTypeDescription
$lengthintThe target length.
$charstringThe padding character (default: empty-space).
$typestringThe padding type (left, right, both).

Return:

self - Returns a new instance with padding applied.

Example:

$str = new Str('Hi');

echo $str->pad(5, '_');
// Hi___

escape

Escape special characters in the string for HTML or attribute context.

public function escape(string $context = 'html', string $encoding = 'UTF-8'): self

Parameters:

ParameterTypeDescription
$contextstringThe value escaper content (Either html or attr) (default 'html').
$encodingstringThe character encoding (default UTF-8).

Return:

self - Returns a new instance with escaped content.

Example:

$str = new Str('<b>Unsafe</b>');

echo $str->escape();
// "&lt;b&gt;Unsafe&lt;/b&gt;"

reverse

Reverse the string.

public function reverse(): self

Return:

self - Returns a new instance with reversed string.

Example:

$str = new Str('abc');

echo $str->reverse(); // "cba"

substring

Extracts a substring from the string using fixed start and optional length.

Unlike slice(), this method does not support negative indexes.It behaves like JavaScript's substring() method — counting only from the beginning of the string.

public function substring(int $start, ?int $length = null): self

Parameters:

ParameterTypeDescription
$startintThe starting index (0-based).
$length?intThe number of characters to extract (null for the rest of the string).

Return:

self - Returns a new instance containing the substring.

Example:

echo Str::of('abcdef')->substring(1, 3); // "bcd"
echo Str::of('abcdef')->substring(2);    // "cdef"

slice

Extracts a section of the string by start and end indexes.

Supports negative indexes, which count from the end of the string. Works like JavaScript's String.prototype.slice(), more flexible than substring(), since you can use both positive and negative positions.

public function slice(int $start, ?int $end = null): self

Parameters:

ParameterTypeDescription
$startintThe starting index (can be negative).
$end?intThe ending index (exclusive). Can be negative or null for full length.

Return:

self - Returns a new Str instance containing the extracted substring.

Example:

echo Str::of('The quick brown fox')->slice(4, 9);  // "quick"
echo Str::of('你好世界')->slice(1, 3);               // "好世"
echo Str::of('The quick brown fox')->slice(-3);    // "fox"
echo Str::of('abcdef')->slice(-4, -1);             // "cde"

mask

Mask part of the string using a specified character.

public function mask(string $character = '*', string $position = 'center'): self

Parameters:

ParameterTypeDescription
$characterstringThe character to use for masking (default '*').
$positionstringThe mask position (left, right;, center).

Return:

self - Returns a new instance with the masked string.

Example:

$str = new Str('SensitiveData');

echo $str->mask('*', 'center');
// "S******ata"

words

Split the string into individual words.

Non-letter or non-number characters are treated as delimiters.

public function words(): array

Return:

string[] - Returns an array of string into words.

Example:

$str = new Str('Hello, world! PHP rocks');

print_r($str->words());
// ["Hello", "world", "PHP", "rocks"]

slugify

Convert the string into a URL-friendly slug.

public function slugify(string $delimiter = '-'): self

Parameters:

ParameterTypeDescription
$delimiterstringThe character used to separate words.

Return:

self - Returns a new instance containing the slug.

Example:

$str = new Str('Hello World!');

echo $str->slugify();
// "hello-world"

truncate

Truncate the string to a specified length.

If the string is longer than the limit, it is shortened gracefully.

public function truncate(int $limit): self

Parameters:

ParameterTypeDescription
$limitintThe maximum string length.

Return:

self - Returns a new instance with the truncated string.

Example:

$str = new Str('This is too long');

echo $str->truncate(7);
// "This is"

wrap

Wrap the string with another string before and/or after.

public function wrap(string $before, string $after): self

Parameters:

ParameterTypeDescription
$beforestringThe value to prepend before string value.
$afterstringThe value to append after string value.

Return:

self - Returns a new instance with wrapped content.

Example:

$str = new Str('text');

echo $str->wrap('<b>', '</b>');
// "<b>text</b>"

between

Extract the text between two substrings.

public function between(string $start, string $end): self

Parameters:

ParameterTypeDescription
$startstringThe starting delimiter.
$endstringThe ending delimiter.

Return:

self - Returns a new instance containing the extracted text or empty string if not found.

Example:

$str = new Str('Hello [John]');

echo $str->between('[', ']');
// "John"

shuffle

Randomly shuffle or select characters from the string.

This method shuffles the string's characters or returns a random subset.If $unique is true, duplicate characters are removed before shuffling.

public function shuffle(?int $length = null, bool $unique = false): self

Parameters:

ParameterTypeDescription
$length?intOptional number of random characters to return.
If null, the entire string is randomized (default null).
$uniqueboolIf true, ensures characters do not repeat in the result.

Return:

self - Returns a new instance containing the randomized string.

Examples:

$str = new Str('abcdefa');

echo $str->shuffle();         // "dfabcea" (varies)
echo $str->shuffle(3);        // "bfa" (varies)
echo $str->shuffle(3, true);  // "cde" (no repeats)
echo $str->shuffle(unique: true); // "abcdef" (duplicates removed, then shuffled)

concat

Concatenate one or more strings to the current string.

public function concat(Stringable|string ...$strings): self

Parameters:

ParameterTypeDescription
$stringsStringable&#124;stringArguments of strings or Stringable objects to append.

Return:

self - Returns a new Str instance containing the concatenated result.

** Example:

$str = Str::of('Hello');
$str2 = Str::of('World');

echo $str->concat(' ', $str2); // "Hello World"

equals

Check if the string equals another string.

public function equals(Stringable|string $value, bool $caseSensitive = true): bool

Parameters:

ParameterTypeDescription
$valueStringable&#124;stringThe string to compare with.
$caseSensitiveboolCompare case-sensitively or not.

Return:

bool - Returns true if equal, false otherwise.

Example:

$str = new Str('Hello');

echo $str->equals('hello'); // false
echo $str->equals('hello', false); // true (case-insensitive)

trim

Trim whitespace or custom characters from both ends.

public function trim(string $characters = " \t\n\r\0\x0B"): self

Parameters:

ParameterTypeDescription
$charactersstringOptional characters to trim.

Return:

self - Returns a new instance with trimmed string.

Example:

$str = new Str('  hello  ');

echo $str->trim();
// "hello"

trimStart

Trim from the beginning only.

public function trimStart(string $characters = " \t\n\r\0\x0B"): self

Parameters:

ParameterTypeDescription
$charactersstringOptional characters to trim.

Return:

self - Returns a new instance with trimmed start.

Example:

echo Str::of('  hello  ')->trimStart(); // "hello  "

trimEnd

Trim from the end only.

public function trimEnd(string $characters = " \t\n\r\0\x0B"): self

Parameters:

ParameterTypeDescription
$charactersstringOptional characters to trim.

Return:

self - Returns a new instance with trimmed end.

Example:

echo Str::of('  hello  ')->trimEnd(); // "  hello"

contains

Check if the string contains another string.

Alias: includes()

public function contains(Stringable|string $needle, bool $caseSensitive = true): bool

Parameters:

ParameterTypeDescription
$needleStringable&#124;stringThe substring to find.
$caseSensitiveboolWhether to match case-sensitively.

Return:

bool - Return true if found, false otherwise.

Example:

if(Str::of('Hello')->contains('ell')){
    echo 'Match found';
}

// Or with alias
if(Str::of('Hello')->includes('ell')){
    echo 'Match found';
}

matches

Test if the string matches a regex pattern.

public function matches(string $pattern): bool

Parameters:

ParameterTypeDescription
$patternstringThe Regular expression to match.

Return:

bool - Return true if it matches, false otherwise.

Example:

if(Str::of('abc123')->matches('/\d+/')){
    echo 'Match found';
}

Find the position of the first match for a regex pattern.

public function search(string $pattern): int

Parameters:

ParameterTypeDescription
$patternstringRegular expression to search for.

Return:

int - Returns the index of the first match, or -1 if not found.

Example:

Works like JavaScript's String.prototype.search().

$str = Str::of("I think Ruth's dog is cuter than your dog!");

$pos = $str->search('/[^\w\s\']/'); // 41
echo $str[$pos]; // "!"

position

Find the position of a substring.

Retrieves the position of the first occurrence of a substring within the string.

public function position(Stringable|string $needle, int $offset = 0, bool $caseSensitive = true): int|bool

Parameters:

ParameterTypeDescription
$needleStringable&#124;stringThe substring to find within the string.
$offsetintThe position to start searching from (default: 0).
$caseSensitiveboolWhether the search should be case-sensitive (default: true).

Return:

int|bool - Returns the position of the first match, or false if not found.

Example:

$str = Str::of('Hello World');

echo $str->position('World');           // 6
echo $str->position('world', caseSensitive: false); // 6 (case-insensitive)
echo $str->position('PHP');             // false

This method works like PHP's native strpos(), but allows optional case-insensitive search when $caseSensitive is set to false.


normalize

Normalize the string to a specified Unicode form.

This method ensures that visually identical Unicode strings are representedconsistently in memory (useful for comparisons, hashing, or storage).

public function normalize(string $form = 'NFC'): self

Parameters:

ParameterTypeDescription
$formstringThe normalization form (Default: NFC).
Accepted values: NFC, NFD, NFKC, NFKD.

Return:

self - Returns a new normalized string instance.

Throws:

Example:

// Characters with combining accents may look identical but differ in code units
$str = new Str("e\u{0301}");   // "e" + "́"

echo $str->normalize('NFC')->toString();  // "é"

Note:Requires the PHP intl extension.


toLowerCase

Transform the string value to lowercase.

public function toLowerCase(): self

Return:

self - Returns a new instance with lowercase text.

Example:

echo Str::of('Hello World')->toUpperCase(); // hello world

toUpperCase

Transform the string value to uppercase.

public function toUpperCase(): self

Return:

self - Returns a new instance with uppercase text.

Example:

echo Str::of('Hello World')->toUpperCase(); // HELLO WORLD

toCamelCase

Transform the string value to camelCase.

public function toCamelCase(): self

Return:

self - Returns a new instance in camelCase format.

Example:

echo Str::of('Hello World')->toCamelCase(); // helloWorld

toPascalCase

Transform the string value to PascalCase.

public function toPascalCase(): self

Return:

self - Returns a new instance in PascalCase format.

Example:

echo Str::of('Hello World')->toPascalCase(); // HelloWorld

toSnakeCase

Transform the string value to snake_case.

public function toSnakeCase(): self

Return:

self - Returns a new instance in snake_case format.

Example:

echo Str::of('Hello World')->toSnakeCase(); // Hello_World

toKebabCase

Transform the string value to kebab-case.

public function toKebabCase(bool $toLowerCase = false): self

Parameters:

ParameterTypeDescription
$toLowerCaseboolWhether to force lowercase.

Return:

self - Returns a new instance in kebab-case format.

Example:

echo Str::of('Hello World')->toKebabCase(); // Hello-World

toWellFormed

Ensure the string is well-formed UTF-8.

Invalid byte sequences will be replaced with the Unicode replacement character (U+FFFD).

public function toWellFormed(): self

Return:

self - A new well-formed string instance.

Example:

echo Str::of("Hello\x80World")->toWellFormed(); // "Hello�World"

toEncoding

Convert the string to a specific encoding.

public function toEncoding(string $toEncoding, ?string $fromEncoding = null): static

Parameters:

ParameterTypeDescription
$toEncodingstringThe target encoding (e.g., UTF-8, ISO-8859-1).
$fromEncoding?stringOptional source encoding. If null, detects automatically.

Return:

static - Returns a new Str instance in the target encoding.

Example:

echo Str::of('Héllo 🌍')->toEncoding('ISO-8859-1'); // "H?llo ?"
echo Str::of('Héllo 🌍')->toEncoding('UTF-8');      // "Héllo 🌍"

toString

Get the transformed string value.

public function toString(): string

Return:

string - Return the final value of string object.

Example:

echo Str::of('Hello')->toString(); // "Hello"

endsWith

Check if the string ends with a specific substring.

If $position is provided, the string is treated as if it were only that long.

public function endsWith(
    Stringable|string $needle,
    ?int $position = null,
    bool $caseSensitive = true
): bool

Parameters:

ParameterTypeDescription
$needleStringable&#124;stringThe substring to check.
$position?intThe end position at which is expected to be found (default: null string length).
$caseSensitiveboolWhether to match case-sensitively (default: true).

Return:

bool - Returns true if the string ends with the given substring.

Examples:

if(Str::of('Hello')->endsWith('o')){
    echo 'Value ends with o';
}

// More examples
Str::of("Hello world")->endsWith("world"); // true
Str::of("Hello world")->endsWith("World", caseSensitive: false); // true (case-insensitive)
Str::of("Hello world")->endsWith("Hello", 5); // true (checks "Hello")

startsWith

Check if the string starts with a specific substring.

public function startsWith(
    Stringable|string $needle,
    ?int $position = null,
    bool $caseSensitive = true
): bool

Parameters:

ParameterTypeDescription
$needleStringable&#124;stringThe substring to check.
$position?intThe start position at which is expected to be found (default: null 0).
$caseSensitiveboolWhether to match case-sensitively (default: true).

Return:

bool - Returns true if the string starts with the given substring.

Example:

if(Str::of('Hello')->startsWith('H')){
    echo 'Value starts with H';
}

// More examples

Str::of("Hello world")->startsWith("Hello"); // true
Str::of("Hello world")->startsWith("hello", caseSensitive: false); // true (case-insensitive)
Str::of("Hello world")->startsWith("world", 6); // true (starts at index 6)

charCodeAt

Get the UTF-16 code unite of the character at a specific index.

public function charCodeAt(int $index): ?int

Parameters:

ParameterTypeDescription
$indexintThe character position (0-based).

Return:

int|null - Returns the 16-bit code unit or null if out of range

Example:

echo Str::of("☃★♲")->charCodeAt(1);   // 9733 (★)
echo Str::of("😀")->charCodeAt(0);     // 55357 (high surrogate)
echo Str::of("😀")->charCodeAt(1);     // 56832 (low surrogate)

codePointAt

Get the Unicode code point at the given position.

This differs from charCodeAt() in that it returns the full Unicode code point, even for surrogate pairs (e.g., emojis or rare symbols).

public function codePointAt(int $index): ?int

Parameters:

ParameterTypeDescription
$indexintThe position of the character.

Return:

int|null - Returns the Unicode code point, or null if out of range.

Example:

echo Str::of('A')->codePointAt(0);     // 65
echo Str::of('你')->codePointAt(0);     // 20320
echo Str::of('😀')->codePointAt(0);     // 128512

isWellFormed

Check whether the string is a well-formed UTF-8 sequence.

This method verifies that all bytes in the string are valid UTF-8 characters.It does not modify the string — it only checks for encoding validity.

public function isWellFormed(): bool

Return:

bool - Returns true if the string is a valid UTF-8 sequence, or false if it contains invalid or malformed bytes.

Example:

echo Str::of('Hello')->isWellFormed();          // true
echo Str::of("Hello\xC0World")->isWellFormed(); // false

isEmpty

Check if the string is empty.

public function isEmpty(): bool

Return:

bool - Returns true if empty, false otherwise.

Example:

if(Str::of('Hello')->isEmpty()){
    echo 'Is empty value';
}

isNumeric

Check if the string is numeric.

public function isNumeric(): bool

Return:

bool - Returns true if numeric, false otherwise.

Example:

if(Str::of('1234567')->isNumeric()){
    echo 'Is Numeric value';
}

isHex

Check if value is a hexadecimal representation.

public function isHex(): bool

Return:

bool - Return true if value is a hexadecimal representation.

Example:

if(Str::of('1234567')->isHex()){
    echo 'Is Hexadecimal value';
}

includes

Alias for contains().

public function includes(Stringable|string $needle, bool $caseSensitive = true): bool

Parameters:

ParameterTypeDescription
$needleStringable&#124;stringThe substring to find.
$caseSensitiveboolWhether to match case-sensitively (default: true).

Return:

bool - Return true if found, false otherwise.


offsetExists

Check whether an index refers to a character.

public function offsetExists(mixed $offset): bool

Parameters:

ParameterTypeDescription
$offsetmixedIndex to test.

Return:

bool - Returns true for an integer index from zero to one less than the string length.


offsetGet

Read a character using the object’s configured encoding.

public function offsetGet(mixed $offset): ?string

Parameters:

ParameterTypeDescription
$offsetintCharacter index.

Return:

string|null - Returns the character, or null if the integer index is outside the string.

Throws:

  • Luminova\Exceptions\InvalidArgumentException - If the offset is not an integer.

offsetSet

Replace the character at an index with the string form of the supplied value.

public function offsetSet(mixed $offset, mixed $value): void

Parameters:

ParameterTypeDescription
$offsetintCharacter index.
$valuemixedReplacement converted to a string.

Throws:

  • Luminova\Exceptions\InvalidArgumentException - If the offset is not an integer.

offsetUnset

Remove the character at an index.

public function offsetUnset(mixed $offset): void

Parameters:

ParameterTypeDescription
$offsetintCharacter index.

Throws:

  • Luminova\Exceptions\InvalidArgumentException - If the offset is not an integer.

assert

Validate the type of a string offset.

public function assert(mixed $offset): void

Parameters:

ParameterTypeDescription
$offsetmixedOffset to validate.

Throws:

  • Luminova\Exceptions\InvalidArgumentException - If the offset is not an integer.