स्पेशल कैरेक्टर जांचना
उदाहरण
<?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 पैटर्न गलत है
मूल regex [@_!#$%^&*()<>?/|}{~:] में समस्याएं हैं:
^और]के बीच-रेंज ऑपरेटर माना जाता है}और{एस्केप नहीं किए गए^कैरेक्टर क्लास की शुरुआत में नेगेशन माना जाता है
सही Regex
<?php
function check_string_fixed($my_string) {
// स्पेशल कैरेक्टर्स: @ _ ! # $ % ^ & * ( ) < > ? / } { ~ :
// सही पैटर्न: सभी मेटा-कैरेक्टर्स एस्केप करें
$pattern = '/[@_!#$%^&*()<>?\/}{~:]/';
// या सरल: अल्फान्यूमेरिक और स्पेस के अलावा कुछ भी
// $pattern = '/[^a-zA-Z0-9\s]/';
if (preg_match($pattern, $my_string)) {
echo "String has special characters: ACCEPTED\n";
} else {
echo "String has no special characters: NOT ACCEPTED\n";
}
}
$test1 = 'This_is_$_sample!'; // _, $, ! - स्पेशल
$test2 = 'HelloWorld123'; // कोई स्पेशल नहीं
$test3 = 'Hello World!'; // ! स्पेशल
check_string_fixed($test1); // ACCEPTED
check_string_fixed($test2); // NOT ACCEPTED
check_string_fixed($test3); // ACCEPTED
?>
आउटपुट
String has special characters: ACCEPTED String has no special characters: NOT ACCEPTED String has special characters: ACCEPTED
स्पेशल कैरेक्टर की परिभाषा
"स्पेशल कैरेक्टर" की परिभाषा उपयोग के मामले पर निर्भर करती है:
- पासवर्ड वैलिडेशन: !@#$%^&*()_+-=[]{}|;:,.<>?
- यूजरनेम: केवल अल्फान्यूमेरिक और अंडरस्कोर
- सामान्य टेक्स्ट: विराम चिह्न अनुमत
ctype फंक्शन्स (Regex विकल्प)
<?php
function hasSpecialChars($str) {
for ($i = 0; $i < strlen($str); $i++) {
$c = $str[$i];
if (!ctype_alnum($c) && $c !== ' ' && $c !== '_') {
return true;
}
}
return false;
}
?>