String Functions
This file contains various utility functions for string manipulation.
nl2brCustom($text)
Convert newlines to HTML line breaks.
Parameters:
string $textThe input text.
Returns:
stringThe text with<br>tags.
Usage:
$htmlText = nl2brCustom("Line 1\nLine 2");
echo $htmlText; // Line 1<br>Line 2
escapeJs($str)
Escape single quotes for JavaScript.
Parameters:
string $strThe input string.
Returns:
stringThe escaped string.
Usage:
$jsString = escapeJs("It's a test.");
echo $jsString; // It\'s a test.
slugify($str)
Generate a URL slug from a string.
Parameters:
string $strThe input string.
Returns:
stringThe URL slug.
Usage:
$slug = slugify('Hello World!');
echo $slug; // hello-world
truncate($str, $length = 100, $append = '...')
Truncate a string to a specified length.
Parameters:
string $strThe input string.int $lengthThe desired length.string $appendThe string to append.
Returns:
stringThe truncated string.
Usage:
$shortText = truncate('This is a long text.', 10);
echo $shortText; // This is a...
startsWith($haystack, $needle)
Check if a string starts with a given substring.
Parameters:
string $haystackThe input string.string $needleThe substring to check.
Returns:
boolTrue if$haystackstarts with$needle, false otherwise.
Usage:
$isStart = startsWith('Hello World', 'Hello');
echo $isStart; // 1 (true)
endsWith($haystack, $needle)
Check if a string ends with a given substring.
Parameters:
string $haystackThe input string.string $needleThe substring to check.
Returns:
boolTrue if$haystackends with$needle, false otherwise.
Usage:
$isEnd = endsWith('Hello World', 'World');
echo $isEnd; // 1 (true)
toUpperCase($str)
Convert a string to uppercase.
Parameters:
string $strThe input string.
Returns:
stringThe uppercase string.
Usage:
$upperStr = toUpperCase('hello');
echo $upperStr; // HELLO
toLowerCase($str)
Convert a string to lowercase.
Parameters:
string $strThe input string.
Returns:
stringThe lowercase string.
Usage:
$lowerStr = toLowerCase('HELLO');
echo $lowerStr; // hello
capitalizeWords($str)
Capitalize the first letter of each word in a string.
Parameters:
string $strThe input string.
Returns:
stringThe capitalized string.
Usage:
$capitalizedStr = capitalizeWords('hello world');
echo $capitalizedStr; // Hello World
strReplace($search, $replace, $subject)
Replace a substring in a string.
Parameters:
string $searchThe substring to search for.string $replaceThe replacement string.string $subjectThe original string.
Returns:
stringThe string with replacements.
Usage:
$newStr = strReplace('world', 'PHP', 'Hello world');
echo $newStr; // Hello PHP
repeatChar($char, $times)
Generate a string of repeated characters.
Parameters:
string $charThe character to repeat.int $timesThe number of times to repeat.
Returns:
stringThe resulting string.
Usage:
$repeated = repeatChar('*', 10);
echo $repeated; // **********