doumaqing6652 2014-11-29 11:32
浏览 358

PHP - 检查字符串中是否包含非法字符

In JS you can do:

 var chs = "[](){}";
 var str = "hello[asd]}";
 if (str.indexOf(chs) != -1) {
    alert("The string can't contain the following characters: " + chs.split("").join(", "));
 }

How can you do this in PHP (replacing alert with echo)?

I do not want to use a regex for the simplicity of what I think.

EDIT:

What I've tried:

 <?php
    $chs = /[\[\]\(\)\{\}]/;
    $str = "hella[asd]}";
    if (preg_match(chs, str)) {
       echo ("The string can't contain the following characters: " . $chs);
    }
 ?>

Which obviously doesn't work and idk how to do it without regex.

  • 写回答

3条回答 默认 最新

  • dongnuo3749 2014-11-29 11:36
    关注

    In php you should do this:

    $string = "Sometring[inside]";
    
    if(preg_match("/(?:\[|\]|\(|\)|\{|\})+/", $string) === FALSE)
    {
         echo "it does not contain.";
    }
    else
    {
         echo "it contains";
    ]
    

    The regex says check to see any of the characters are inside the string. you can read more about it here:

    http://en.wikipedia.org/wiki/Regular_expression

    And about PHP preg_match() :

    http://php.net/manual/en/function.preg-match.php

    Update:

    I have written an updated regex for this, which captures the letters inside:

    $rule = "/(?:(?:\[([\s\da-zA-Z]+)\])|\{([\d\sa-zA-Z]+)\})|\(([\d\sa-zA-Z]+)\)+/"
    $matches = array();
    if(preg_match($rule, $string, $matches) === true)
    {
       echo "It contains: " . $matches[0];
    }
    

    It returnes something like this:

    It contains: [inside]
    

    I have changed the regex only which becomes:

    $rule = "/(?:(?:(\[)(?:[\s\da-zA-Z]+)(\]))|(\{)(?:[\d\sa-zA-Z]+)(\}))|(\()(?:[\d\sa-zA-Z]+)(\))+/";
    

    // it returns an array of occurred illegal characters

    It now returns [] for this "I am [good]"

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。