To check if a string has a special character, the PHP code is as follows;
Example
<?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); ?>
Output
String has not been accepted
Above, a function named ‘check_string’ is defined, that takes a string as its parameter −
$my_string = 'This_is_$_sample!';
Use regular expression to check if a string has a special character. If there is a special character, a specific message is printed. Outside the function, the string is defined, and the function is called by passing the string as parameter −
function check_string($my_string){ $regex = preg_match('[@_!#$%^&*()<>?/|}{~:]', $my_string); if($regex) print("String has been accepted"); else print("String has not been accepted"); }