Kotchasan Framework Documentation
Text Class - Text Manipulation Utilities
Text Class - Text Manipulation Utilities
The Text class provides various text manipulation methods including string truncation, file size formatting, sanitization, and format conversion.
Namespace
Kotchasan\TextOverview
Text class is a utility class with static methods for:
- String cutting and formatting
- Escaping and sanitizing data for security
- Filtering and converting data by patterns
- Generating random strings
- Managing text for HTML, URLs, usernames, passwords
API Reference
cut()
Truncate text to specified length (uses .. two dots)
public static function cut(string $source, int $len): stringParameters:
$source- Source text$len- Desired length (including..)
Returns: Truncated text with .. if exceeded
Example:
use Kotchasan\Text;
$text = "This is a long text that needs to be truncated";
echo Text::cut($text, 20); // "This is a long t.."
echo Text::cut($text, 10); // "This is .."
echo Text::cut("Short", 20); // "Short" (not truncated)formatFileSize()
Convert file size from bytes to KB, MB, GB
public static function formatFileSize(int $bytes, int $precision = 2): stringParameters:
$bytes- File size in bytes$precision- Decimal places (default: 2)
Returns: Readable file size
Example:
echo Text::formatFileSize(1024); // "1 KB"
echo Text::formatFileSize(1048576); // "1 MB"
echo Text::formatFileSize(1073741824); // "1 GB"
echo Text::formatFileSize(1500000, 1); // "1.4 MB"
echo Text::formatFileSize(0); // "0 Byte"highlighter()
Convert BBCode and URLs to HTML
public static function highlighter(string $detail): stringParameters:
$detail- Text with BBCode or URLs
Returns: Converted HTML
Example:
$text = "[b]Bold text[/b] and visit https://example.com";
echo Text::highlighter($text);
// "<strong>Bold text</strong> and visit <a href=\"https://example.com\" target=\"_blank\">https://example.com</a>"
$text = "[url=https://google.com]Click here[/url]";
echo Text::highlighter($text);
// "<a href=\"https://google.com\" target=\"_blank\">Click here</a>"htmlspecialchars()
Convert special characters to HTML entities
public static function htmlspecialchars(string $text, bool $double_encode = true): stringParameters:
$text- Source text$double_encode- Double encode or not (default: true)
Returns: Escaped text
Example:
echo Text::htmlspecialchars("<script>alert('XSS')</script>");
// "<script>alert('XSS')</script>"
echo Text::htmlspecialchars("Price: $100 & tax");
// "Price: $100 & tax"
echo Text::htmlspecialchars("A \"quote\" & 'apostrophe'");
// "A "quote" & 'apostrophe'"oneLine()
Convert text to single line (remove line breaks and extra spaces)
public static function oneLine(string $text, int $len = 0): stringParameters:
$text- Source text$len- Maximum length (0 = unlimited)
Returns: Single line text
Example:
$text = "Line 1\nLine 2\n Line 3 ";
echo Text::oneLine($text); // "Line 1 Line 2 Line 3"
$text = "A B C";
echo Text::oneLine($text); // "A B C" (removes extra spaces)
echo Text::oneLine("Long text here", 10); // "Long te.."password()
Filter text to password-safe characters only
public static function password(string $text): stringParameters:
$text- Source text
Returns: Filtered text (only a-z, 0-9, @#*$&{}!?+_-=.[]ก-ฮ)
Example:
echo Text::password("Pass@123!"); // "Pass@123!"
echo Text::password("P@ss<script>"); // "P@ss" (removes <script>)
echo Text::password("รหัส_123"); // "รหัส_123"removeNonCharacters()
Remove invalid UTF-8 bytes
public static function removeNonCharacters(string $text): stringParameters:
$text- Source text
Returns: Text with invalid bytes removed
Example:
$clean = Text::removeNonCharacters($userInput);repeat()
Repeat text specified number of times
public static function repeat(string $text, int $count): stringParameters:
$text- Text to repeat$count- Number of times
Returns: Repeated text
Example:
echo Text::repeat("*", 5); // "*****"
echo Text::repeat("AB", 3); // "ABABAB"
echo Text::repeat("-", 10); // "----------"replace()
Replace values in text using array
public static function replace(string $source, array $replace): stringParameters:
$source- Source text$replace- Array of key => value for replacement
Returns: Replaced text
Example:
$template = "Hello {name}, you have {count} messages";
$data = ['{name}' => 'John', '{count}' => 5];
echo Text::replace($template, $data);
// "Hello John, you have 5 messages"
$text = "Price: {price}, Tax: {tax}";
echo Text::replace($text, ['{price}' => '$100', '{tax}' => '$10']);
// "Price: $100, Tax: $10"toEditor()
Convert special characters for editor
public static function toEditor(string $text): stringParameters:
$text- Source text
Returns: Escaped text for editor
Example:
$code = '<div class="test">content</div>';
echo Text::toEditor($code);
// "<div class="test">content</div>"topic()
Clean text (remove HTML tags, invalid chars, normalize whitespace)
public static function topic(string $text, int $len = 0): stringParameters:
$text- Source text$len- Maximum length (0 = unlimited)
Returns: Cleaned text
Example:
$html = "<h1>Title</h1>\n<p>Content</p>";
echo Text::topic($html); // "TitleContent" (removes HTML and merges to one line)
$text = "<b>Bold</b> and <i>italic</i>";
echo Text::topic($text, 10); // "Bold and.."unhtmlspecialchars()
Convert HTML entities back to normal characters
public static function unhtmlspecialchars(string $text): stringParameters:
$text- Text with HTML entities
Returns: Converted text
Example:
echo Text::unhtmlspecialchars("<div>");
// "<div>"
echo Text::unhtmlspecialchars("Price: $100 & tax");
// "Price: $100 & tax"url()
Sanitize URL string
public static function url(string $text): stringParameters:
$text- Source URL
Returns: Safe URL
Example:
echo Text::url("https://example.com");
// "https://example.com"
echo Text::url("javascript:alert('XSS')");
// "alert('XSS')" (removes javascript:)
echo Text::url("https://test.com?a=1&b=2");
// "https://test.com?a=1&b=2"username()
Sanitize username (allow only a-z, 0-9, @, ., -, _)
public static function username(string $text): stringParameters:
$text- Source username
Returns: Safe username
Example:
echo Text::username("john.doe@example"); // "john.doe@example"
echo Text::username("user_123"); // "user_123"
echo Text::username("user<script>"); // "userscript"
echo Text::username("test-user.2024"); // "test-user.2024"generateRandomString()
Generate random string
public static function generateRandomString(int $length = 4, string $characters = '0123456789'): stringParameters:
$length- Length$characters- Characters to use
Returns: Random string
Example:
echo Text::generateRandomString(6); // "438291"
echo Text::generateRandomString(8, 'ABCDEF0123456789'); // "A3F2E1D9"
echo Text::generateRandomString(10, 'abcdefghijklmnopqrstuvwxyz'); // "ksjdhfgqwe"filter()
Filter text by pattern
public static function filter(?string $text, string $pattern, string $replacement = ''): stringParameters:
$text- Source text$pattern- Regex character class pattern$replacement- Replacement text (default: '')
Returns: Filtered text
Example:
echo Text::filter("abc123xyz", "a-z"); // "abcxyz"
echo Text::filter("test@#$123", "a-zA-Z0-9"); // "test123"
echo Text::filter("Hello World!", "a-zA-Z", "-"); // "Hello-World"alphanumeric()
Filter to alphanumeric only
public static function alphanumeric(?string $text): stringParameters:
$text- Source text
Returns: Only a-z, A-Z, 0-9
Example:
echo Text::alphanumeric("abc123xyz"); // "abc123xyz"
echo Text::alphanumeric("test-user_123"); // "testuser123"
echo Text::alphanumeric("hello@world.com"); // "helloworldcom"phone()
Filter to digits only (for phone numbers)
public static function phone(?string $text): stringParameters:
$text- Source text
Returns: Digits only
Example:
echo Text::phone("081-234-5678"); // "0812345678"
echo Text::phone("+66 81 234 5678"); // "660812345678" (+ is also removed)
echo Text::phone("(081) 234-5678"); // "0812345678"color()
Validate and sanitize color value (hex or pure alphabetic)
public static function color(?string $text, string $default = ''): stringParameters:
$text- Color value$default- Default if invalid/empty
Returns: Valid color or default (if invalid/empty)
Valid Formats:
- Hex colors:
#RGB,#RRGGBB,#RRGGBBAA(e.g.,#F00,#FF0000) - Alphabetic strings: pure a-Z (e.g.,
red,blue,invalid) - does NOT validate against actual CSS color names
Example:
echo Text::color("#FF0000"); // "#FF0000"
echo Text::color("#F00"); // "#F00"
echo Text::color("red"); // "red"
echo Text::color("invalid123", "#000000"); // "#000000" (has numbers → uses default)
echo Text::color("", "#000000"); // "#000000" (uses default because empty)
echo Text::color("#ZZZZZZ", "black"); // "black" (invalid hex → uses default)
echo Text::color("invalid"); // "invalid" (pure alphabetic is accepted)quote()
Escape single quotes to HTML entity
public static function quote(?string $text): stringParameters:
$text- Source text
Returns: Escaped text
Example:
echo Text::quote("It's great"); // "It's great"
echo Text::quote("John's book"); // "John's book"textarea()
Escape text for textarea display
public static function textarea(?string $text): stringParameters:
$text- Source text
Returns: Escaped text
Example:
$text = '<script>alert("XSS")</script>';
echo Text::textarea($text);
// "<script>alert("XSS")</script>"number()
Filter to digits only
public static function number(?string $text): stringParameters:
$text- Source text
Returns: Digits 0-9 only
Example:
echo Text::number("abc123xyz"); // "123"
echo Text::number("Price: $99.99"); // "9999"
echo Text::number("-123.45"); // "12345"toDouble()
Convert text to decimal
public static function toDouble(?string $text): floatParameters:
$text- Source text
Returns: Decimal value
Example:
echo Text::toDouble("123.45"); // 123.45
echo Text::toDouble("1,234.56"); // 1234.56 (removes comma)
echo Text::toDouble("99.9"); // 99.9
echo Text::toDouble(""); // 0keywords()
Sanitize and truncate keywords
public static function keywords(?string $text, int $len = 0): stringParameters:
$text- Source text$len- Maximum length (0 = unlimited)
Returns: Clean keywords
Example:
$text = "<b>PHP</b>, MySQL, Laravel";
echo Text::keywords($text); // "PHP, MySQL, Laravel"
echo Text::keywords("web development programming", 15); // "web development"description()
Sanitize description (remove HTML, BBCode, widgets)
public static function description(?string $text, int $len = 0): stringParameters:
$text- Source text$len- Maximum length (0 = unlimited)
Returns: Clean description
Example:
$html = "<p>This is a <strong>description</strong></p>";
echo Text::description($html); // "This is a description"
$text = "[b]Bold[/b] and [i]italic[/i]";
echo Text::description($text); // "Bold and italic"detail()
Escape text for editor content
public static function detail(?string $text): stringParameters:
$text- Source text
Returns: Escaped text
Example:
$code = "<?php echo 'test'; ?>";
echo Text::detail($code); // " echo 'test'; " (removes <?php ?>)
$text = "Price: {$100}";
echo Text::detail($text); // "Price: {$100}"time()
Parse and validate time format
public static function time(?string $text, bool $strict = false): ?stringParameters:
$text- Time (HH:MM or HH:MM:SS)$strict- Add :00 if no seconds
Returns: Validated time or null
Example:
echo Text::time("14:30"); // "14:30"
echo Text::time("14:30", true); // "14:30:00"
echo Text::time("14:30:45"); // "14:30:45"
echo Text::time("invalid"); // nulldate()
Parse and format date
public static function date(?string $text, string $format = 'Y-m-d'): ?stringParameters:
$text- Date (various formats)$format- Output format
Returns: Formatted date or null
Example:
echo Text::date("2024-01-15"); // "2024-01-15"
echo Text::date("2024-01-15", "d/m/Y"); // "15/01/2024"
echo Text::date("15 Jan 2024"); // "2024-01-15"
echo Text::date("invalid"); // nullhtmlText()
Allow only specific HTML tags
public static function htmlText(string $text, bool $double_encode = true, array $allowedTags = ['em', 'b', 'strong', 'i']): stringParameters:
$text- Source text$double_encode- Double encode or not$allowedTags- Allowed tags
Returns: Text with only allowed tags
Example:
$text = "<b>Bold</b> and <script>evil</script>";
echo Text::htmlText($text);
// "<b>Bold</b> and evil" (removes script tag)
$text = "<em>Italic</em> and <div>block</div>";
echo Text::htmlText($text, true, ['em']);
// "<em>Italic</em> and block" (only em remains)Real-World Examples
1. Form Input Sanitization
use Kotchasan\Text;
class UserController
{
public function register($data)
{
$username = Text::username($data['username']);
$email = filter_var($data['email'], FILTER_VALIDATE_EMAIL);
$phone = Text::phone($data['phone']);
$password = Text::password($data['password']);
// Save to database
}
}2. Display Safe Content
class PostController
{
public function show($id)
{
$post = Post::find($id);
return [
'title' => Text::topic($post->title, 100),
'excerpt' => Text::description($post->content, 200),
'content' => Text::htmlText($post->content, true, ['b', 'i', 'em', 'strong', 'a']),
'author' => Text::htmlspecialchars($post->author)
];
}
}3. File Upload Display
class FileManager
{
public function listFiles($files)
{
foreach ($files as $file) {
echo $file['name'] . ' (' . Text::formatFileSize($file['size']) . ')';
}
}
}4. Template Engine
class SimpleTemplate
{
public function render($template, $data)
{
return Text::replace($template, $data);
}
}
$tpl = new SimpleTemplate();
echo $tpl->render(
"Hello {name}, Total: {price}",
['{name}' => 'John', '{price}' => '$100']
);Best Practices
1. Choose Appropriate Method
// ❌ Bad - wrong method
$username = Text::htmlspecialchars($_POST['username']);
// ✅ Good - specific method
$username = Text::username($_POST['username']);2. Sanitize Before Display
// ✅ Good - escape before display
echo Text::htmlspecialchars($userInput);
// ❌ Dangerous - direct output
echo $userInput; // XSS vulnerability!3. Use for Validation
$color = Text::color($_POST['color'], '#000000');
$time = Text::time($_POST['time']);
$phone = Text::phone($_POST['phone']);
if (empty($phone)) {
throw new Exception("Invalid phone number");
}Important Considerations
[!WARNING]
XSS Prevention: Always usehtmlspecialchars()or appropriate method before displaying user input[!CAUTION]
Data Loss: Some methods permanently remove data (e.g.,filter(),alphanumeric()) - verify before use[!NOTE]
Null Safety: Most methods handlenulland empty strings gracefully by returning empty string[!TIP]
Performance: For large data, usingmb_*functions directly may be faster
Related Classes
- ArrayTool - Array manipulation utilities
- Input - Input validation and filtering
- Validator - Data validation
Summary
The Text class provides 31 methods for various text manipulations, perfect for:
- Security: Sanitize and escape data to prevent XSS
- Validation: Validate data formats (username, phone, color, time, date)
- Formatting: Format text (cut, oneLine, formatFileSize)
- Filtering: Filter text by conditions (alphanumeric, number, phone)
- Transformation: Transform text (BBCode, HTML entities, templates)
All methods are static and can be called directly without creating an instance.