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+ 浏览量

开启你的 职业生涯

完成课程,取得证书

开始
广告
© . All rights reserved.