PHP 程式用於檢查字串中是否包含特殊字元


檢查字串中是否包含特殊字元的 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");
}

更新於: 2020 年 8 月 17 日

8k+ 瀏覽量

開啟你的 職業生涯

完成課程,取得證書

開始
廣告