Luminova Framework

PHP Luminova: PHP Common Helpers

Last updated: 2026-01-17 19:56:37

The common helpers provide a set of static utility methods for formatting, validating, and normalizing data. They include features such as string and email masking, phone number formatting, and more

The common Helpers class offers a collection of static utility methods that simplify and standardize data handling across your application. It enhances development efficiency by providing ready-to-use solutions for common tasks.

Key features include:

  • Input Formatting: Normalize various input types for consistency and reliability.
  • Email & Phone Validation: Ensure emails and phone numbers meet standard formats and regional rules.
  • Random String Generation: Generate secure random strings for tokens, identifiers, and more.
  • EAN/UPC Generation: Create valid product codes for inventory and retail use.
  • UUID Generation: Generate universally unique identifiers for reliably identifying records.
  • Email & String Masking: Obscure sensitive data to enhance privacy and security.

Class Definition

  • Class namespace: Luminova\Utility\Helpers

Methods

The methods can be accessed statically.

use Luminova\Utility\Helpers;

echo Helpers::random(50, 'string');

normalize

Format text before display by matching links, email, phone, hashtags and mentions with a link representation and replace multiple line breaks.

public static normalize(string $text, string $target = '_self', string $blocked = null, bool $noHtml = true): string

Parameters:

ParameterTypeDescription
$textstringText to be formatted
$targetstringLink target attribute in HTML anchor name.
-@example [_blank, _self, _top, _window, _parent or frame name]
$blockedstringReplace blocked word with
$noHtmlboolDetermines whether to remove all HTML tags or only allow certain tags like <p> by default, it's set to true.

Return Value:

string - Return the formatted text.


random

Generate a random string or value.

public static random(int $length = 10, string $type = 'int', bool $uppercase = false): string

Parameters:

ParameterTypeDescription
$lengthintThe length of the random value to generate.
$typestringThe type of random value to generate (e.g., character, alphabet, int, password, bytes, hex).
$uppercaseboolWhether to convert non-numeric values to uppercase (default: false).

Return Value:

string - Return the generated randomized value.

Supported Types:

  • character - Includes special characters like %#*^,?+$;"{}][|\/:=)(@!.-.
  • alphabet - Contains only alphabetical characters (both uppercase and lowercase).
  • password - Combines letters, numbers, and an expanded set of special characters (%#^_-@!$&*+=|~?<>[]{}()).
  • bytes - Returns a raw binary string of the specified length.
  • hex - Returns a hexadecimal representation of random bytes.
  • int|integer - Contains only numeric characters (0-9).

Examples:

Generates a secure password of 16 characters.

Helpers::random(16, 'password');

Generates an 8-character string in uppercase letters.

Helpers::random(8, 'alphabet', true);

Generates a 32-character hexadecimal string.

Helpers::random(32, 'hex');

ean

Generate product EAN13 id.

public static ean(int $country = 615, int $length = 13): string

Parameters:

ParameterTypeDescription
$countryintThe start prefix country code.
$lengthintThe maximum length.

Return Value:

string - Return the generated product ean code.


upc

Generate a product UPC ID.

public static upc(int $prefix, int $length = 12): string

Parameters:

ParameterTypeDescription
$prefixintThe start prefix number.
$lengthintThe maximum length.

Return Value:

string - Return the generated UPC ID.


uuid

Generates a UUID string of the specified version.

public static uuid(int $version = 4, ?string $namespace = null, ?string $name = null): string

Parameters:

ParameterTypeDescription
$versionintThe version of the UUID to generate (1, 2, 3, 4, or 5).
$namespacestring|nullThe namespace for versions 3 and 5.
$namestring|nullThe name for versions 3 and 5.

Return Value:

string - Return the generated UUID string.

Throws:


isUuid

Validates a UUID string against a specific version.

public static isUuid(string $uuid, int $version = 4): bool

Parameters:

ParameterTypeDescription
$uuidstringThe UUID string to check.
$versionintThe UUID version to check (default: 4).

Return Value:

bool - Return true if the UUID is valid, false otherwise.


isEmail

Checks if string is a valid email address, with optional support for internationalized domains.

public static isEmail(string $email, bool $allow_idn = false): bool

Parameters:

ParameterTypeDescription
$emailstringThe email address to validate.
$allow_idnboolSet to true to allow internationalized domains (default: false).

Return Value:

bool - Returns true if valid email address, false otherwise.


isPhone

Validates if the input is a valid phone number.

public static isPhone(string|int $phone, int $min = 10, int $max = 15): bool

Parameters:

ParameterTypeDescription
$phonestring|intThe phone address to validate
$minintThe minimum allowed length allowed (default: 10).
$maxintThe maximum allowed length (default: 15).

Return Value:

bool - Returns true if valid phone number, false otherwise.


isUrl

Checks if the string is a valid URL, with optional support for internationalized domains.

public static isUrl(string $url, bool $allowIdn = false, bool $http_only = false): bool

Parameters:

ParameterTypeDescription
$urlstringThe URL to validate.
$allowIdnboolSet to true to allow internationalized domains (default: false).
$http_onlyboolWhether to support urls with http and https scheme (default: false).

Return Value:

bool - Returns true if valid URL, false otherwise.


isBase64Encoded

Determines whether the given string is Base64-encoded (standard, URL-safe, or MIME style).

Supports both standard URL-safe, and MIME-safe Base64 strings (with newlines).

public static isBase64Encoded(string $data, bool $strict = true): bool

Parameters:

ParameterTypeDescription
$datastringThe input string to validate.
$strictboolIf true, base64_decode() will return false on invalid characters.

Return Value:

bool - Returns true if the string appears to be valid Base64; false otherwise.


isBinary

Determines if the content string is likely a binary based on the presence of non-printable characters.

public static isBinary(string $data): bool

Parameters:

ParameterTypeDescription
$datastringThe string to check for binary.

Return Value:

bool - Return true if it's a binary, false otherwise.


formatPhone

Formats a phone number as (xxx) xxx-xxxx or xxx-xxxx depending on the length.

public static formatPhone(string $phone): string

Parameters:

ParameterTypeDescription
$phonestringThe phone address to format.

Return Value:

string - Return the formatted phone number.


strength

Determine if password strength matches the basic strength recommendation.

public static strength(string $password, int $complexity = 4, int $min = 6, int $max = 50): bool

Parameters:

ParameterTypeDescription
$passwordstringThe password string to check.
$complexityintThe maximum complexity pass count 4 means password must contain (numbers, uppercase, lowercase and special characters).
$minintThe minimum allowed password length (default: 6).
$maxintThe maximum allowed password length (default: 50).

Return Value:

bool - Return true if password passed, otherwise false.


sanitize

Sanitize or validate user input based on the specified type.

Strictly sanitizes user input to protect against invalid characters and ensures it conforms to the expected type. It can either validate only or replace disallowed characters with a given replacement.

Additionally this method can easily be used from it global helper functions Luminova\Funcs\sanitize(...) and Luminova\Funcs\strict(...).

public static sanitize(string $value, string $type = 'name', ?string $replacement = ''): ?string

Parameters:

ParameterTypeDescription
$valuestringThe input string value to be sanitized.
$typestringThe expected data type (e.g., 'int', 'email', 'username').
$replacementstring|nullThe symbol to replace disallowed characters (default: '' blank).
- If string, invalid characters are replaced with this symbol.
- If null, the method throws an exception when the input is invalid.

Return Value:

string|null - Returns the sanitized string, or null if input could not be sanitized and $replacement is provided.

Throws:

If:

  • $replacement = null and the value does not match the type.
  • The $type is not supported.

Supported Types:

TypeDescription
intOnly numeric digits (0-9).
numeric / digitNumeric values including negative and decimal numbers
keyAlphanumeric, underscore, hyphen.
passwordStrict password pattern: uppercase, lowercase, digits, special chars. Replacement not allowed.
username3–30 chars: letters, digits, underscore, hyphen, dot. Replacement not allowed.
emailValid email characters. Replacement not allowed.
urlURL-safe characters. Replacement not allowed.
moneyNumeric values, optional decimal, optional negative.
doubleFloating point numbers.
alphabetLetters only (a-z, A-Z).
phoneDigits, +, -.
nameUnicode letters, digits, spaces, apostrophes, underscores, dots, hyphens.
timezoneLetters, numbers, slash, underscore, colon, hyphen.
timeNumeric and colon, e.g., HH:MM:SS.
dateYYYY-MM-DD or YYYY-MM-DD HH:MM:SS.
uuidStandard UUID format 8-4-4-4-12 hex.
defaultRemoves HTML tags; allows any other characters.

Note:

Types marked as “Replacement not allowed” only support validation; $replacement is ignored.

Examples:

Int type (strip HTML)

use Luminova\Utility\Helpers;

$input = '1235hJndhb@<script>alert("hello");</script>';
Helpers::sanitize($input, 'int'); // Returns 1235

Sanitize numeric input

use Luminova\Utility\Helpers;

$value = Helpers::sanitize('1234', 'int'); // 1234
$value = Helpers::sanitize('12.34', 'numeric'); // 12.34

Validate only, throws exception on invalid input

use Luminova\Utility\Helpers;

Helpers::sanitize('abc123', 'int', null); // Throws InvalidArgumentException

Replace invalid characters

use Luminova\Utility\Helpers;

$value = Helpers::sanitize('abc$123', 'key', '_'); // abc_123

Default type (strip HTML)

use Luminova\Utility\Helpers;

$value = Helpers::sanitize('<b>Hello</b> World'); // Hello World

Unsupported type

use Luminova\Utility\Helpers;

Helpers::sanitize('value', 'unknown'); // Throws InvalidArgumentException

Note:

  • Numeric shortcuts (int, numeric) efficiently bypass regex when input is already valid.
  • HTML tags are removed automatically for non-default types if $replacement is not null.
  • Use $replacement = null for strict validation only, otherwise replacement mode is applied.
  • HTML tags (including their content) are completely removed for the any type.

This ensures secure handling of input to prevent invalid characters or unsafe content.


mainDomain

Remove subdomains from a URL and return the main domain name only.

public static mainDomain(string $url): string

Parameters:

ParameterTypeDescription
$urlstringThe input URL from which subdomains should be removed.

Return Value:

string - Return the main domain extracted from the URL.


subdomain

Remove main domain from a URL and return only the first subdomain name.

public static subdomain(string $url): string

Parameters:

ParameterTypeDescription
$urlstringThe input URL from which the domain should be extracted.

Return Value:

string - Return the extracted domain or an empty string if no domain is found.

Note: www is considered as none subdomain.And only the first level of subdomain will be returned if the url contains multiple levels of subdomain.


truncate

Truncate a string in specified length and adds an ellipsis at the end if the text is longer than the specified length.

public static truncate(string $text, int $length = 10, string $encoding = 'UTF-8'): string

Parameters:

ParameterTypeDescription
$textstringThe string to truncate.
$lengthintThe length to display before truncating.
$encodingstringThe text encoding type.

Return Value:

string - Return the truncated string.


base64UrlEncode

Convert a string to base64 encode in other to pass it as a URL parameter.

public static base64UrlEncode(string $input): string

Parameters:

ParameterTypeDescription
$inputstringThe string to encode.

Return Value:

string - Return base64 encoded string url.


base64UrlDecode

Decode a URL Base64 decoded string back to it's original content.

public static base64UrlDecode(string $input): string

Parameters:

ParameterTypeDescription
$inputstringThe base64 encoded URL string to decode.

Return Value:

string - Return base64 decoded string.


maskEmail

Mask an email address to hide part of it (e.g pe***[email protected]).

public static maskEmail(string $email, string $masker = '*'): string

Parameters:

ParameterTypeDescription
$emailstringThe email address to mask.
$maskerstringThe mask character (default: *).

Return Value:

string - Return masked email address.


mask

Mask a string by position to hide part of it (e.g: mfk****kld).

public static mask(string $string, string $masker = '*', string $position = 'center'): string

Parameters:

ParameterTypeDescription
$stringstringThe string to mask.
$maskerstringThe mask character (default: *).
$positionstringThe position of the string to mask (center, left, or right).

Return Value:

string - Return masked string.


hexToBinary

Converts a hexadecimal string into its binary representation.

public static hexToBinary(string $hexStr, ?string $destination = null): string|bool

Parameters:

ParameterTypeDescription
$hexStrstringThe input string containing hexadecimal data.
$destinationstring|nullOptional. If specified, saves the binary data to a file.
- If it's a file path, the binary data is saved directly.
- If it's a directory, a unique filename is generated.

Return Value:

string|bool - Return the binary string if no destination is provided. If a file is written, returns true on success, false on failure.

Throws: