หลายวิธีในการลบ Whitespace (Space, Tab, Newline) ออกจาก String ใน PHP เลือกตามความต้องการ
1. ลบ Space แค่ Space Character (ASCII 32)
$str = "this is a test string";
// str_replace - เร็วที่สุดสำหรับ Space เดียว
$result = str_replace(' ', '', $str);
// "thisisateststring"
// strtr - เร็วกว่าเล็กน้อยสำหรับหลาย Character
$result = strtr($str, [' ' => '']);
// "thisisateststring"
2. ลบ Whitespace ทั้งหมด (Space, Tab, Newline, Carriage Return)
$str = "this\tis\na test\rstring";
// preg_replace - ใช้ Regex \s (Whitespace ทุกประเภท)
$result = preg_replace('/\s+/', '', $str);
// "thisisateststring"
// str_replace หลายตัว (ไม่รองรับ \r\n ทุกケース)
$result = str_replace([" ", "\t", "\n", "\r"], '', $str);
3. ลบ Whitespace เฉพาะหน้า/หลัง (Trim)
$str = " hello world ";
// Trim ทั้ง 2 ด้าน
trim($str); // "hello world"
// เฉพาะหน้า
ltrim($str); // "hello world "
// เฉพาะหลัง
rtrim($str); // " hello world"
// Custom Characters
trim($str, " \t\n\r\0\x0B"); // Default
rtrim($str, ",.! "); // ลบตัวอักษรเฉพาะที่ท้าย
4. ลบ Whitespace ซ้ำ (Collapse Multiple Spaces)
$str = "this is a test";
// Regex: แทนที่ Whitespace หลายตัวเป็น Space เดียว
$result = preg_replace('/\s+/', ' ', $str);
// "this is a test"
// Trim ด้วย
$result = trim(preg_replace('/\s+/', ' ', $str));
5. Unicode Whitespace (PHP 7.4+ / PCRE2)
$str = "hello\u{3000}world"; // Ideographic Space (Full-width Space)
// \s ใน PCRE2 (PHP 7.3+) รองรับ Unicode Whitespace
$result = preg_replace('/\s+/u', '', $str);
// "helloworld"
// กรณีเก่า: ต้องระบุเอง
$result = preg_replace('/[\x20\x09\x0A\x0D\x0B\xA0\u{3000}]+/u', '', $str);
Benchmark (String 1MB, 50% Whitespace)
/* ประมาณ:
str_replace(' ', ''): 0.002s (Space only)
strtr($str, [' ' => '']): 0.0018s
preg_replace('/\s+/', ''): 0.015s (Regex Overhead)
preg_replace('/ /', ''): 0.012s
*/
// str_replace/strtr เร็วกว่า Regex มากสำหรับ Space ธรรมดา
สรุป: เลือกใช้ตัวไหน?
| ความต้องการ | ฟังก์ชัน | ตัวอย่าง |
|---|---|---|
| ลบ Space ธรรมดา (เร็วที่สุด) | str_replace(' ', '', $str) | "a b c" → "abc" |
| ลบ Whitespace ทั้งหมด (\s) | preg_replace('/\s+/', '', $str) | "a\tb\nc" → "abc" |
| ลบ Space หน้า/หลัง | trim($str) | " a " → "a" |
| Collapse Multiple Spaces | preg_replace('/\s+/', ' ', $str) | "a b" → "a b" |
| Unicode Whitespace | preg_replace('/\s+/u', '', $str) | Full-width Space |