Kotchasan Framework Documentation
Text Class - เครื่องมือจัดการข้อความ
Text Class - เครื่องมือจัดการข้อความ
คลาส Text มีเมธอดสำหรับจัดการข้อความหลากหลายรูปแบบ รวมถึงการตัดข้อความ, การแปลงขนาดไฟล์, การ sanitize ข้อมูล, และการแปลงรูปแบบต่างๆ
Namespace
Kotchasan\Textภาพรวม
Text class เป็น utility class ที่มีเมธอด static สำหรับ:
- การตัดและจัดรูปแบบข้อความ
- การ escape และ sanitize ข้อมูลเพื่อความปลอดภัย
- การกรองและแปลงข้อมูลตามรูปแบบต่างๆ
- การสร้างข้อความสุ่ม
- การจัดการข้อความสำหรับ HTML, URL, username, password
API Reference
cut()
ตัดข้อความให้สั้นลงตามความยาวที่กำหนด (ใช้ .. สองจุด)
public static function cut(string $source, int $len): stringParameters:
$source- ข้อความต้นฉบับ$len- ความยาวที่ต้องการ (รวม..)
Returns: ข้อความที่ถูกตัด พร้อม .. ถ้าเกินความยาว
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" (ไม่ถูกตัด)formatFileSize()
แปลงขนาดไฟล์จาก bytes เป็น KB, MB, GB
public static function formatFileSize(int $bytes, int $precision = 2): stringParameters:
$bytes- ขนาดไฟล์เป็น bytes$precision- จำนวนทศนิยม (default: 2)
Returns: ขนาดไฟล์ในรูปแบบที่อ่านง่าย
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()
แปลง BBCode และ URL เป็น HTML
public static function highlighter(string $detail): stringParameters:
$detail- ข้อความที่มี BBCode หรือ URL
Returns: 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()
แปลงอักขระพิเศษเป็น HTML entities
public static function htmlspecialchars(string $text, bool $double_encode = true): stringParameters:
$text- ข้อความต้นฉบับ$double_encode- encode ซ้ำหรือไม่ (default: true)
Returns: ข้อความที่ escape แล้ว
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()
แปลงข้อความให้เป็น 1 บรรทัด (ลบ line breaks และช่องว่างเกิน)
public static function oneLine(string $text, int $len = 0): stringParameters:
$text- ข้อความต้นฉบับ$len- ความยาวสูงสุด (0 = ไม่จำกัด)
Returns: ข้อความ 1 บรรทัด
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" (ลบช่องว่างเกิน)
echo Text::oneLine("Long text here", 10); // "Long te.."password()
กรองข้อความให้เหลือเฉพาะอักขระที่ใช้ได้ใน password
public static function password(string $text): stringParameters:
$text- ข้อความต้นฉบับ
Returns: ข้อความที่กรองแล้ว (เหลือ a-z, 0-9, @#*$&{}!?+_-=.[]ก-ฮ)
Example:
echo Text::password("Pass@123!"); // "Pass@123!"
echo Text::password("P@ss<script>"); // "P@ss" (ลบ <script>)
echo Text::password("รหัส_123"); // "รหัส_123"removeNonCharacters()
ลบอักขระที่ไม่ใช่ UTF-8 ที่ถูกต้อง
public static function removeNonCharacters(string $text): stringParameters:
$text- ข้อความต้นฉบับ
Returns: ข้อความที่ลบ invalid bytes แล้ว
Example:
$clean = Text::removeNonCharacters($userInput);repeat()
ทำซ้ำข้อความตามจำนวนที่กำหนด
public static function repeat(string $text, int $count): stringParameters:
$text- ข้อความที่ต้องการทำซ้ำ$count- จำนวนครั้ง
Returns: ข้อความที่ทำซ้ำ
Example:
echo Text::repeat("*", 5); // "*****"
echo Text::repeat("AB", 3); // "ABABAB"
echo Text::repeat("-", 10); // "----------"replace()
แทนที่ค่าในข้อความด้วย array
public static function replace(string $source, array $replace): stringParameters:
$source- ข้อความต้นฉบับ$replace- array ของ key => value สำหรับแทนที่
Returns: ข้อความที่แทนที่แล้ว
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()
แปลงอักขระพิเศษสำหรับ editor
public static function toEditor(string $text): stringParameters:
$text- ข้อความต้นฉบับ
Returns: ข้อความที่ escape สำหรับ editor
Example:
$code = '<div class="test">content</div>';
echo Text::toEditor($code);
// "<div class="test">content</div>"topic()
ทำความสะอาดข้อความ (ลบ HTML tags, invalid chars, normalize whitespace)
public static function topic(string $text, int $len = 0): stringParameters:
$text- ข้อความต้นฉบับ$len- ความยาวสูงสุด (0 = ไม่จำกัด)
Returns: ข้อความที่สะอาด
Example:
$html = "<h1>Title</h1>\n<p>Content</p>";
echo Text::topic($html); // "TitleContent" (ลบ HTML และรวมเป็นบรรทัดเดียว)
$text = "<b>Bold</b> and <i>italic</i>";
echo Text::topic($text, 10); // "Bold and.."unhtmlspecialchars()
แปลง HTML entities กลับเป็นอักขระปกติ
public static function unhtmlspecialchars(string $text): stringParameters:
$text- ข้อความที่มี HTML entities
Returns: ข้อความที่แปลงกลับแล้ว
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- URL ต้นฉบับ
Returns: URL ที่ปลอดภัย
Example:
echo Text::url("https://example.com");
// "https://example.com"
echo Text::url("javascript:alert('XSS')");
// "alert('XSS')" (ลบ javascript:)
echo Text::url("https://test.com?a=1&b=2");
// "https://test.com?a=1&b=2"username()
Sanitize username (อนุญาตเฉพาะ a-z, 0-9, @, ., -, _)
public static function username(string $text): stringParameters:
$text- username ต้นฉบับ
Returns: 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()
สร้างข้อความสุ่ม
public static function generateRandomString(int $length = 4, string $characters = '0123456789'): stringParameters:
$length- ความยาว$characters- อักขระที่ใช้สร้าง
Returns: ข้อความสุ่ม
Example:
echo Text::generateRandomString(6); // "438291"
echo Text::generateRandomString(8, 'ABCDEF0123456789'); // "A3F2E1D9"
echo Text::generateRandomString(10, 'abcdefghijklmnopqrstuvwxyz'); // "ksjdhfgqwe"filter()
กรองข้อความตาม pattern
public static function filter(?string $text, string $pattern, string $replacement = ''): stringParameters:
$text- ข้อความต้นฉบับ$pattern- regex character class pattern$replacement- ข้อความแทนที่ (default: '')
Returns: ข้อความที่กรองแล้ว
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()
กรองเหลือเฉพาะตัวอักษรและตัวเลข
public static function alphanumeric(?string $text): stringParameters:
$text- ข้อความต้นฉบับ
Returns: เฉพาะ 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()
กรองเหลือเฉพาะตัวเลข (สำหรับเบอร์โทร)
public static function phone(?string $text): stringParameters:
$text- ข้อความต้นฉบับ
Returns: เฉพาะตัวเลข
Example:
echo Text::phone("081-234-5678"); // "0812345678"
echo Text::phone("+66 81 234 5678"); // "660812345678" (+ จะถูกลบเหมือนกัน)
echo Text::phone("(081) 234-5678"); // "0812345678"color()
ตรวจสอบและ sanitize สี (hex หรือตัวอักษรล้วน)
public static function color(?string $text, string $default = ''): stringParameters:
$text- ค่าสี$default- ค่า default ถ้า invalid/empty
Returns: สีที่ถูกต้อง หรือ default (ถ้า invalid/empty)
Valid Formats:
- Hex colors:
#RGB,#RRGGBB,#RRGGBBAA(e.g.,#F00,#FF0000) - Alphabetic strings: ตัวอักษร a-Z ล้วน (e.g.,
red,blue,invalid) - ไม่ตรวจสอบว่าเป็น CSS color name จริง
Example:
echo Text::color("#FF0000"); // "#FF0000"
echo Text::color("#F00"); // "#F00"
echo Text::color("red"); // "red"
echo Text::color("invalid123", "#000000"); // "#000000" (มีตัวเลขปน → ใช้ default)
echo Text::color("", "#000000"); // "#000000" (ใช้ default เพราะ empty)
echo Text::color("#ZZZZZZ", "black"); // "black" (hex ไม่ถูก → ใช้ default)
echo Text::color("invalid"); // "invalid" (ยอมรับเพราะเป็นตัวอักษรล้วน)quote()
Escape เครื่องหมาย single quote
public static function quote(?string $text): stringParameters:
$text- ข้อความต้นฉบับ
Returns: ข้อความที่ escape แล้ว
Example:
echo Text::quote("It's great"); // "It's great"
echo Text::quote("John's book"); // "John's book"textarea()
Escape ข้อความสำหรับ textarea
public static function textarea(?string $text): stringParameters:
$text- ข้อความต้นฉบับ
Returns: ข้อความที่ escape แล้ว
Example:
$text = '<script>alert("XSS")</script>';
echo Text::textarea($text);
// "<script>alert("XSS")</script>"number()
กรองเหลือเฉพาะตัวเลข
public static function number(?string $text): stringParameters:
$text- ข้อความต้นฉบับ
Returns: เฉพาะตัวเลข 0-9
Example:
echo Text::number("abc123xyz"); // "123"
echo Text::number("Price: $99.99"); // "9999"
echo Text::number("-123.45"); // "12345"toDouble()
แปลงข้อความเป็นทศนิยม
public static function toDouble(?string $text): floatParameters:
$text- ข้อความต้นฉบับ
Returns: ค่าทศนิยม
Example:
echo Text::toDouble("123.45"); // 123.45
echo Text::toDouble("1,234.56"); // 1234.56 (ลบ comma)
echo Text::toDouble("99.9"); // 99.9
echo Text::toDouble(""); // 0keywords()
Sanitize และตัดคำสำคัญ
public static function keywords(?string $text, int $len = 0): stringParameters:
$text- ข้อความต้นฉบับ$len- ความยาวสูงสุด (0 = ไม่จำกัด)
Returns: คำสำคัญที่สะอาด
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 (ลบ HTML, BBCode, widgets)
public static function description(?string $text, int $len = 0): stringParameters:
$text- ข้อความต้นฉบับ$len- ความยาวสูงสุด (0 = ไม่จำกัด)
Returns: 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 ข้อความสำหรับ editor content
public static function detail(?string $text): stringParameters:
$text- ข้อความต้นฉบับ
Returns: ข้อความที่ escape แล้ว
Example:
$code = "<?php echo 'test'; ?>";
echo Text::detail($code); // " echo 'test'; " (ลบ <?php ?>)
$text = "Price: {$100}";
echo Text::detail($text); // "Price: {$100}"time()
Parse และ validate รูปแบบเวลา
public static function time(?string $text, bool $strict = false): ?stringParameters:
$text- เวลา (HH:MM or HH:MM:SS)$strict- เพิ่ม :00 ถ้าไม่มีวินาที
Returns: เวลาที่ validate แล้ว หรือ 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 และ format วันที่
public static function date(?string $text, string $format = 'Y-m-d'): ?stringParameters:
$text- วันที่ (รูปแบบต่างๆ)$format- รูปแบบ output
Returns: วันที่ที่ format แล้ว หรือ 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()
อนุญาตเฉพาะ HTML tags บางตัว
public static function htmlText(string $text, bool $double_encode = true, array $allowedTags = ['em', 'b', 'strong', 'i']): stringParameters:
$text- ข้อความต้นฉบับ$double_encode- encode ซ้ำหรือไม่$allowedTags- tags ที่อนุญาต
Returns: ข้อความที่มีเฉพาะ tags ที่อนุญาต
Example:
$text = "<b>Bold</b> and <script>evil</script>";
echo Text::htmlText($text);
// "<b>Bold</b> and evil" (ลบ script tag)
$text = "<em>Italic</em> and <div>block</div>";
echo Text::htmlText($text, true, ['em']);
// "<em>Italic</em> and block" (เหลือแค่ em)ตัวอย่างการใช้งานจริง
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']);
// บันทึกลงฐานข้อมูล
}
}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. เลือกเมธอดให้เหมาะกับการใช้งาน
// ❌ ไม่ดี - ใช้ผิดเมธอด
$username = Text::htmlspecialchars($_POST['username']);
// ✅ ดี - ใช้เมธอดเฉพาะทาง
$username = Text::username($_POST['username']);2. Sanitize ข้อมูลก่อนแสดงผล
// ✅ ดี - escape ข้อมูลก่อนแสดง
echo Text::htmlspecialchars($userInput);
// ❌ อันตราย - แสดงโดยตรง
echo $userInput; // XSS vulnerability!3. ใช้ช่วยการทำ 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: ใช้htmlspecialchars()หรือเมธอดที่เหมาะสมก่อนแสดงข้อมูลจาก user ทุกครั้ง[!CAUTION]
Data Loss: เมธอดบางตัวจะลบข้อมูลถาวร (เช่นfilter(),alphanumeric()) ตรวจสอบให้แน่ใจก่อนใช้[!NOTE]
Null Safety: เมธอดส่วนใหญ่จัดการnullและ empty string ได้ โดย return empty string[!TIP]
Performance: สำหรับข้อมูลขนาดใหญ่ ใช้mb_*functions โดยตรงจะเร็วกว่า
Related Classes
- ArrayTool - Array manipulation utilities
- Input - Input validation and filtering
- Validator - Data validation
สรุป
คลาส Text มีเมธอด 31 ตัวสำหรับจัดการข้อความหลากหลายรูปแบบ เหมาะสำหรับ:
- Security: Sanitize และ escape ข้อมูลเพื่อป้องกัน XSS
- Validation: ตรวจสอบรูปแบบข้อมูล (username, phone, color, time, date)
- Formatting: จัดรูปแบบข้อความ (cut, oneLine, formatFileSize)
- Filtering: กรองข้อความตามเงื่อนไข (alphanumeric, number, phone)
- Transformation: แปลงข้อความ (BBCode, HTML entities, template)
เมธอดทั้งหมดเป็น static สามารถเรียกใช้ได้โดยตรงโดยไม่ต้องสร้าง instance