คำอธิบาย
MySQL ไม่มีฟังก์ชัน substr_replace() เหมือน PHP แต่มีฟังก์ชัน INSERT() ที่ทำงานคล้ายกัน สามารถแทนที่ส่วนหนึ่งของสตริงได้
รูปแบบฟังก์ชัน INSERT()
INSERT(str, pos, len, newstr)
- str: สตริงต้นฉบับ
- pos: ตำแหน่งเริ่มต้น (เริ่มที่ 1)
- len: จำนวนตัวอักษรที่จะแทนที่
- newstr: สตริงใหม่ที่จะแทนที่
คืนค่า NULL หากอาร์กิวเมนต์ใดเป็น NULL
ขั้นตอนการสร้างตารางและข้อมูลตัวอย่าง
mysql> create table DemoTable (
Password varchar(50) );
Query OK, 0 rows affected (0.51 sec)
การเพิ่มข้อมูล
mysql> insert into DemoTable values('76367_____8793443');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('12345_____9899984322');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('99999_____4747747432');
Query OK, 1 row affected (0.22 sec)
แสดงข้อมูลทั้งหมด
mysql> select * from DemoTable;
ผลลัพธ์:
+----------------------+ | Password | +----------------------+ | 76367_____8793443 | | 12345_____9899984322 | | 99999_____4747747432 | +----------------------+ 3 rows in set (0.00 sec)
คิวรี่แทนที่อักขระ 5 ตัวแรกหลังตำแหน่งที่ 5 ด้วย 'PPPPPP'
mysql> select insert(Password, 5, length('PPPPPP'), 'PPPPPP') from DemoTable;
ผลลัพธ์
+----------------------------------------------+
| insert(Password,5,length('PPPPPP'),'PPPPPP') |
+----------------------------------------------+
| 7636PPPPPP8793443 |
| 1234PPPPPP9899984322 |
| 9999PPPPPP4747747432 |
+----------------------------------------------+
3 rows in set (0.00 sec)
คำอธิบาย
- เริ่มที่ตำแหน่งที่ 5 (อักขระที่ 5)
- แทนที่จำนวนตัวอักษรเท่ากับความยาวของ 'PPPPPP' (6 ตัว)
- แทนที่ด้วยสตริง 'PPPPPP'
- เหมาะสำหรับการ masking ข้อมูล เช่น บัตรเครดิต เบอร์โทรศัพท์