PHP program to check if a string has a special character

PHPServer Side ProgrammingProgramming

To check if a string has a special character, the PHP code is as follows;

Example

 Live Demo

<?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");
}
raja
Published on 17-Aug-2020 15:00:33
Advertisements