The StringHelper
class in JiFramework provides a comprehensive set of methods for manipulating and processing strings. It simplifies common string operations such as escaping HTML characters, generating random strings, formatting text, and more. By leveraging this class, developers can handle string functionality efficiently and consistently across their applications.
Key Features:
- String Escaping: Securely escape special HTML characters to prevent XSS attacks.
- Random Generators: Generate random integers, tokens, strings, and hexadecimal colors.
- String Formatting: Format strings as currency, mask sensitive information, and pad numbers with zeros.
- Text Extraction: Extract integers from strings, get first words from sentences, and extract text from HTML content.
- Case Conversion: Convert strings to camelCase, snake_case, and generate URL-friendly slugs.
- Utility Functions: Check if a string starts or ends with a given substring, truncate strings, and more.
Usage Options:
// Option 1: Initialize the StringHelper through the App
use JIFramework\Core\App\App;
$app = new App();
$stringHelper = $app->stringHelper; // Assuming the App class provides an instance
// Option 2: Instantiate the StringHelper directly
use JIFramework\Core\Utilities\StringHelper;
$stringHelper = new StringHelper();
Explanation:
- Option 1: Initializes the
App
class and retrieves theStringHelper
instance through it, using the framework's main entry point. - Option 2: Directly creates an instance of the
StringHelper
class.
Method: escape($data)
Description: Escapes special HTML characters in a string to prevent XSS attacks. If an array or object is provided, it recursively escapes all strings within it.
Parameters:
- $data (
mixed
): The data to escape (string, array, or object).
Returns: The escaped data of the same type as input.
Usage:
// Escaping a string
$unsafeString = "<script>alert('XSS');</script>";
$safeString = $stringHelper->escape($unsafeString);
/*
Sample $safeString:
"<script>alert('XSS');</script>"
*/
echo $safeString;
// Escaping an array
$dataArray = ['name' => "John", 'age' => 30];
$safeArray = $stringHelper->escape($dataArray);
/*
Sample $safeArray:
[
'name' => "John",
'age' => 30
]
*/
Explanation:
- Converts special HTML characters to their HTML entities.
- Protects against Cross-Site Scripting (XSS) attacks by neutralizing scripts.
- Works recursively on arrays and objects to escape all string values.
Method: generateRandomInteger(int $min, int $max): int
Description: Generates a random integer between the specified minimum and maximum values.
Parameters:
- $min (
int
): The minimum value of the range. - $max (
int
): The maximum value of the range.
Returns: A random integer between $min
and $max
.
Usage:
$randomInt = $stringHelper->generateRandomInteger(1, 100);
/*
Sample $randomInt:
42
*/
echo "Random Integer: " . $randomInt;
Explanation:
- Uses
mt_rand()
for better performance overrand()
. - Useful for generating random IDs, codes, or for testing purposes
Method: generateToken(int $length): string
Description: Creates a secure cryptographic token of the specified length.
Parameters:
- $length (
int
): The length of the token in bytes before hexadecimal encoding.
Returns: A hexadecimal string representing the generated token.
Usage:
$token = $stringHelper->generateToken(16);
echo "Generated Token: " . $token;
/*
Sample $token:
Generated Token: 9f86d081884c7d659a2feaa0c55ad015
*/
Explanation:
- Uses
openssl_random_pseudo_bytes()
to generate cryptographically secure bytes. - Converts the binary data to hexadecimal representation using
bin2hex()
. - Commonly used for session tokens, CSRF tokens, or password reset links.
Method: strLength(string $string): int
Description: Calculates the length of a string.
Parameters:
- $string (
string
): The string to measure.
Returns: The number of characters in $string
.
Usage:
$length = $stringHelper->strLength("Hello World");
/*
Sample $length:
11
*/
echo "String Length: " . $length;
Explanation:
- Uses
strlen()
to get the length of the string. - Note that
strlen()
counts bytes, so for multibyte strings, consider usingmb_strlen()
.
Method: maskString(string $string, int $unmaskedChars = 4, string $maskingCharacter = 'X'): string
Description:
Masks a string by replacing a portion of it with a specified masking character, leaving the last $unmaskedChars
characters visible.
Parameters:
- $string (
string
): The original string to mask. - $unmaskedChars (
int
, optional): Number of characters to leave unmasked at the end. Default is4
. - $maskingCharacter (
string
, optional): The character used for masking. Default is'X'
.
Returns: The masked string.
Usage:
$maskedString = $stringHelper->maskString("1234567890");
/*
Sample $maskedString:
"XXXXXX7890"
*/
echo "Masked String: " . $maskedString;
Explanation:
- Calculates the number of characters to mask.
- Replaces the initial portion of the string with the masking character.
- Useful for hiding sensitive information like credit card numbers or social security numbers.
Method: extractInteger(string $string): int
Description: Extracts all numeric digits from a string and returns them as an integer.
Parameters:
- $string (
string
): The input string containing numbers and other characters.
Returns: The extracted integer.
Usage:
$intValue = $stringHelper->extractInteger("Order #12345A");
/*
Sample $intValue:
12345
*/
echo "Extracted Integer: " . $intValue;
Explanation:
- Uses
preg_replace()
to remove all non-digit characters. - Converts the remaining string to an integer using
intval()
.
Method: padWithZeros(int $number, int $targetLength): string
Description: Prefixes a number with zeros to reach a specified total length.
Parameters:
- $number (
int
): The original number. - $targetLength (
int
): The desired total length of the output string.
Returns: The number as a string, prefixed with zeros.
Usage:
$paddedNumber = $stringHelper->padWithZeros(42, 5);
/*
Sample $paddedNumber:
"00042"
*/
echo "Padded Number: " . $paddedNumber;
Explanation:
- Uses
str_pad()
withSTR_PAD_LEFT
to add zeros to the beginning of the number. - Useful for formatting numbers like order IDs, invoice numbers, or codes.
Method: getFirstWords(string $sentence, int $count = 10): string
Description: Retrieves the first $count
words from a sentence.
Parameters:
- $sentence (
string
): The input sentence. - $count (
int
, optional): The number of words to extract. Default is10
.
Returns: A string containing the first $count
words.
Usage:
$firstWords = $stringHelper->getFirstWords("The quick brown fox jumps over the lazy dog", 4);
/*
Sample $firstWords:
"The quick brown fox"
*/
echo "First Words: " . $firstWords;
Explanation:
- Splits the sentence into words using
preg_split()
. - Extracts the desired number of words and joins them back into a string.
Method: extractTextFromHtml(string $htmlContent, int $wordCount = 10): string
Description: Extracts plain text from HTML content and retrieves the first $wordCount
words.
Parameters:
- $htmlContent (
string
): The HTML content to process. - $wordCount (
int
, optional): The number of words to extract. Default is10
.
Returns: A string containing the extracted plain text.
Usage:
$htmlContent = "The quick brown fox jumps over the lazy dog.";
$extractedText = $stringHelper->extractTextFromHtml($htmlContent, 5);
/*
Sample $extractedText:
"The quick brown fox jumps"
*/
echo "Extracted Text: " . $extractedText;
Explanation:
- Removes HTML tags using
strip_tags()
. - Decodes HTML entities with
html_entity_decode()
. - Splits the text into words and extracts the desired number.
Method: formatCurrency(float $number, int $decimalPlaces = 2, string $currencySymbol = '', string $decimalPoint = '.', string $thousandsSep = ','): string
Description: Formats a number as currency with specified decimal places, currency symbol, and separators.
Parameters:
- $number (
float
): The number to format. - $decimalPlaces (
int
, optional): Number of decimal places. Default is2
. - $currencySymbol (
string
, optional): Currency symbol to prepend. Default is''
. - $decimalPoint (
string
, optional): Decimal point character. Default is'.'
. - $thousandsSep (
string
, optional): Thousands separator. Default is','
.
Returns: The formatted currency string.
Usage:
$formattedCurrency = $stringHelper->formatCurrency(1234.567);
/*
Sample $formattedCurrency:
"1,234.57"
*/
$formattedCurrencyWithSymbol = $stringHelper->formatCurrency(1234.567, 2, '$');
/*
Sample $formattedCurrencyWithSymbol:
"$1,234.57"
*/
echo "Formatted Currency: " . $formattedCurrencyWithSymbol;
Explanation:
- Uses
number_format()
to format the number. - Allows customization of decimal places and symbols.
- Useful for displaying prices, totals, or monetary values.
Method: generateRandomHexColor(): string
Description: Generates a random hexadecimal color code.
Parameters: None
Returns: A string representing the hexadecimal color code (e.g., #1a2b3c
).
Usage:
$hexColor = $stringHelper->generateRandomHexColor();
/*
Sample $hexColor:
"#a1b2c3"
*/
echo "Random Hex Color: " . $hexColor;
Explanation:
- Generates random values for red, green, and blue components.
- Pads each component to ensure two hexadecimal digits.
- Combines them into a standard 6-digit hexadecimal color code.
Method: generateRandomString(int $length = 10): string
Description: Generates a random alphanumeric string of the specified length.
Parameters:
- $length (
int
, optional): The length of the string to generate. Default is10
.
Returns: The generated random string.
Usage:
$randomString = $stringHelper->generateRandomString(12);
/*
Sample $randomString:
"f3D8kLmZ0q1B"
*/
echo "Random String: " . $randomString;
Explanation:
- Uses a predefined set of characters (digits, lowercase, and uppercase letters).
- Randomly selects characters using
mt_rand()
. - Useful for generating passwords, codes, or identifiers.
Method: truncateString(string $string, int $length, string $ellipsis = '...'): string
Description: Truncates a string to a specified length, optionally adding an ellipsis if truncated.
Parameters:
- $string (
string
): The input string. - $length (
int
): The maximum length of the output string. - $ellipsis (
string
, optional): The ellipsis to append if truncated. Default is'...'
.
Returns: The truncated string.
Usage:
$truncated = $stringHelper->truncateString("The quick brown fox jumps over the lazy dog", 20);
/*
Sample $truncated:
"The quick brown fox..."
*/
echo "Truncated String: " . $truncated;
Explanation:
- Checks if the string length exceeds the specified length.
- Truncates the string and appends the ellipsis if necessary.
- Useful for shortening text in UI elements like previews or summaries.
Method: slugify(string $string): string
Description: Converts a string into a URL-friendly "slug" by removing or replacing special characters.
Parameters:
- $string (
string
): The input string.
Returns: The slugified string.
Usage:
$slug = $stringHelper->slugify("Hello World! This is a test.");
/*
Sample $slug:
"hello-world-this-is-a-test"
*/
echo "Slug: " . $slug;
Explanation:
- Converts the string to lowercase.
- Removes HTML tags and non-alphanumeric characters.
- Replaces spaces and special characters with hyphens.
- Ensures the slug is not empty; returns
'n-a'
if so. - Useful for creating SEO-friendly URLs.
Method: toCamelCase(string $string): string
Description: Converts a string to camelCase notation.
Parameters:
- $string (
string
): The input string.
Returns: The camelCased string.
Usage:
$camelCase = $stringHelper->toCamelCase("hello_world_test");
/*
Sample $camelCase:
"helloWorldTest"
*/
echo "CamelCase: " . $camelCase;
Explanation:
- Replaces hyphens and underscores with spaces.
- Capitalizes the first letter of each word.
- Removes spaces and converts the first character to lowercase.
- Useful for converting database field names or IDs to camelCase variables.
Method: toSnakeCase(string $string): string
Description: Converts a string to snake_case notation.
Parameters:
- $string (
string
): The input string.
Returns: The snake_cased string.
Usage:
$snakeCase = $stringHelper->toSnakeCase("HelloWorldTest");
/*
Sample $snakeCase:
"hello_world_test"
*/
echo "SnakeCase: " . $snakeCase;
Explanation:
- Inserts underscores between words.
- Converts uppercase letters to lowercase.
- Trims leading and trailing underscores.
- Useful for standardizing variable names or database fields.
Method: startsWith(string $haystack, string $needle): bool
Description: Checks if a string starts with a given substring.
Parameters:
- $haystack (
string
): The string to search in. - $needle (
string
): The substring to search for.
Returns: true
if $haystack
starts with $needle
, false
otherwise.
Usage:
$startsWithHello = $stringHelper->startsWith("Hello World", "Hello");
/*
Sample $startsWithHello:
true
*/
echo $startsWithHello ? "Starts with 'Hello'" : "Does not start with 'Hello'";
Explanation:
- Compares the beginning of
$haystack
with$needle
. - Useful for conditional checks or routing based on prefixes.
Method: endsWith(string $haystack, string $needle): bool
Description: Checks if a string ends with a given substring.
Parameters:
- $haystack (
string
): The string to search in. - $needle (
string
): The substring to search for.
Returns: true
if $haystack
ends with $needle
, false
otherwise.
Usage:
$endsWithWorld = $stringHelper->endsWith("Hello World", "World");
/*
Sample $endsWithWorld:
true
*/
echo $endsWithWorld ? "Ends with 'World'" : "Does not end with 'World'";
Explanation:
- Compares the end of
$haystack
with$needle
. - Useful for file extension checks or URL suffixes.