ในการตรวจสอบว่าสตริงมีอักขระพิเศษหรือไม่ โค้ด PHP มีดังต่อไปนี้
ตัวอย่าง
<?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
ด้านบน มีการกำหนดฟังก์ชันชื่อ 'check_string' ซึ่งรับสตริงเป็นพารามิเตอร์ -
$my_string = 'This_is_$_sample!';
ใช้นิพจน์ทั่วไปเพื่อตรวจสอบว่าสตริงมีอักขระพิเศษหรือไม่ หากมีอักขระพิเศษ ข้อความเฉพาะจะถูกพิมพ์ นอกฟังก์ชัน มีการกำหนดสตริง และเรียกใช้ฟังก์ชันโดยข้ามสตริงเป็นพารามิเตอร์ -
function check_string($my_string){
$regex = preg_match('[@_!#$%^&*()<>?/|}{~:]', $my_string);
if($regex)
print("String has been accepted");
else
print("String has not been accepted");
}