Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP ตรวจสอบ Special Characters ใน String

ตัวอย่างโค้ด

<?php
function check_string($my_string) {
    $regex = preg_match('[@_!#$%^&*()<>?/|}{~:]', $my_string);
    if ($regex) {
        print("String has been accepted");
    } else {
        print("String has not been accepted");
    }
}

$my_string = 'This_is_$_sample!';
check_string($my_string);
?>

ผลลัพธ์

String has not been accepted

ปัญหาของ Regex ต้นฉบับ

Pattern [@_!#$%^&*()<>?/|}{~:] มีปัญหา:

  • ] ต้อง Escape หรือวางต้น Pattern
  • - ต้อง Escape หรือวางท้าย
  • ^ ต้องไม่ใช่ตัวแรกใน Character Class
  • Delimiters ขาด (ต้องมี /pattern/ หรือ ~pattern~)

Regex ที่ถูกต้อง

<?php
function check_string_fixed($my_string) {
    // ใช้ ~ เป็น Delimiter เพื่อหลีกเลี่ยง / ใน Pattern
    $regex = preg_match('~[@_!#$%^&*()<>?/|}{~:\-\[\]]~', $my_string);
    if ($regex) {
        echo "String has special characters: ACCEPTED";
    } else {
        echo "String has NO special characters: REJECTED";
    }
}

// Test
check_string_fixed('This_is_$_sample!');  // ACCEPTED (มี _ $ !)
check_string_fixed('HelloWorld123');      // REJECTED
?>

คำอธิบาย Pattern

  • ~ ... ~ - Delimiters
  • [@_!#$%^&*()<>?/|}{~:\-\[\]] - Character Class ของ Special Chars
  • \- - Escape Hyphen
  • \[\] - Escape Square Brackets

Alternative: ctype_alnum

เช็คว่าเป็น Alphanumeric เท่านั้น (ไม่มี Special Chars):

<?php
function hasSpecialChars($str) {
    return !ctype_alnum(str_replace([' ', '-', '_'], '', $str));
    // หรือ Custom Logic ตามความต้องการ
}
?>