ตัวอย่างโค้ด
<?php
$my_str = "Thisis!@sample*on&ly)#$";
$my_str = preg_replace('/[^a-z0-9]/i', '', $my_str);
echo "The non-alphanumeric characters removed gives the string as " . $my_str;
?>
ผลลัพธ์
The non-alphanumeric characters removed gives the string as Thisissampleonly
คำอธิบาย Regex
/[^a-z0-9]/i- Character Class แบบ Negative (^ ภายใน [] = NOT)a-z0-9- อักษรอังกฤษ + ตัวเลขi- Case-insensitive Flag- Match อะไรก็ตามที่ ไม่ใช่ Alphanumeric → Replace ด้วย Empty String
ตัวอย่างที่ 2: ใช้ \W (Non-word Characters)
<?php
$my_str = "This!#is^&*a)(sample*+_only";
$my_str = preg_replace('/\W/', '', $my_str);
echo "Result: " . $my_str;
?>
ผลลัพธ์
Result: Thisisasampleonly
หมายเหตุ: \W = [^a-zA-Z0-9_] (เก็บ Underscore _ ไว้) ตัวอย่างแรกลบ _ ด้วย เพราะ Pattern ไม่รวม _
Unicode Support (Thai, Emoji, etc.)
<?php
$str = "Hello สวัสดี 🌟 World!";
echo preg_replace('/[^\p{L}\p{N}]/u', '', $str); // Keep Unicode Letters + Numbers
// HelloสวัสดีWorld
// Keep Thai + English + Numbers only
echo preg_replace('/[^\p{Thai}a-zA-Z0-9]/u', '', $str); // HelloสวัสดีWorld
?>
Performance
preg_replaceช้ากว่าstr_replaceแต่ยืดหยุ่นกว่า- สำหรับ Simple Replacements ใช้
str_replaceหรือstrtr - Compile Regex Pattern หนึ่งครั้ง แล้ว Reuse (ไม่สร้างใน Loop)