代码之家  ›  专栏  ›  技术社区  ›  Scott

如何检查字符串是否在数组中?

  •  5
  • Scott  · 技术社区  · 14 年前

    我的代码到目前为止还不起作用,但它还是在这里,

    $allowedChars = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","0","1","2","3","4","5","6","7","8","9"," ","@",".","-","_","+"," ");
    
    $input = "Test";
    $input = str_split($input);
    
    if (in_array($input,$allowedChars)) {echo "Yep, found.";}else {echo "Sigh, not found...";}
    

    如果$input中有一个字母在 $allowedChars

    顺便说一句,我希望它只是那些数组的值,我不是在寻找花哨的html\u strip\u实体或其他什么东西,我想用那个精确的数组作为允许的字符。

    5 回复  |  直到 9 年前
        1
  •  6
  •   Stephen    14 年前

    您真的应该研究regex和preg\u match函数: http://php.net/manual/en/function.preg-match.php

    但是,这将使您的特定请求生效:

    $allowedChars = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","0","1","2","3","4","5","6","7","8","9"," ","@",".","-","_","+"," ");
    $input = "Test";
    $input = str_split($input);
    $message = "Sigh, not found...";
    foreach($input as $letter) {
        if (in_array($letter, $allowedChars)) {
            $message = "Yep, found.";
            break;
        }
    }
    echo $message;
    
        2
  •  4
  •   mickmackusa    7 年前

    你熟悉正则表达式吗?这是一种更被接受的方式来做你想做的事情,除非我遗漏了什么。

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

    为了说明您的示例,下面是一些示例代码( 更新以解决评论中的问题 ):

    $subject = "Hello, this is a string";
    $pattern = '/[a-zA-Z0-9 @._+-]*/'; // include all the symbols you want to match here
    
    if (preg_match($pattern, $subject))
        echo "Yep, matches";
    else
        echo "Doesn't match :(";
    

    对regex的一点解释是:“^”匹配字符串的开头,“[A-zA-Z0-9@.+-]”部分表示“这个集合中的任何字符”,后面的“*”表示“最后的零个或多个”,最后结尾的“$”匹配字符串的结尾。

        3
  •  1
  •   karim79    14 年前

    有点不同的方法:

    $allowedChars = array("a","b","c","d","e");
    $char_buff = explode('', "Test");
    $foundTheseOnes = array_intersect($char_buff, $allowedChars);
    if(!empty($foundTheseOnes)) {
        echo 'Yep, something was found. Let\'s find out what: <br />';
        print_r($foundTheseOnes);
    }
    
        4
  •  1
  •   mickmackusa    7 年前

    验证字符串中的字符最合适的方法是使用字符串函数。
    preg_match() 是完成此任务最直接/最优雅的方法。

    代码:( Demo )

    $input="Test Test Test Test";
    if(preg_match('/^[\w +.@_-]*$/',$input)){
        echo "Input string does not contain any disallowed characters";
    }else{
        echo "Input contains one or more disallowed characters";
    }
    // output: Yes, input contains only allowed characters
    

    图案说明:

    /          # start pattern
    ^          # start matching from start of string
    [\w +.@-]  # match: a-z, A-Z, 0-9, underscore, space, plus, dot, atsign, hyphen
    *          # zero or more occurrences
    $          # match until end of string
    /          # end pattern
    

    要点:

    • 这个 ^ $ 锚定对于确保验证整个字符串而不仅仅是字符串的子字符串是至关重要的。
    • 这个 \w (a.k.a.“任何单词字符”->一 shorthand character class )最简单的写作方法是: [a-zA-Z0-9_]
    • 这个 . dot character 当它写在字符类中时,就失去了“匹配任何东西(几乎)”的意思,变成了文字。不需要转义斜杠。
    • 连字号 character class \- )只要它位于字符类的开头或结尾。如果连字符不在开始/结束处并且没有转义,它将在其两侧的字符之间创建一个字符范围。
      [.-z] 将不匹配连字符符号,因为它不存在于点字符和小写字母z之间 ascii table .
    • 这个 * 字符类后面的是“ quantifier ". 星号表示前面字符类的“0或更多”。在这种情况下,这意味着 预匹配() + 表示前面字符类的“1个或多个”。最后,通过在一个花括号表达式中使用一个或多个数字,可以更具体地描述字符串长度。
      • {8} 意味着字符串必须正好有8个字符长。
      • {4,}
      • {,10} 意味着字符串长度必须介于0和10之间。
      • {5,9} 意味着字符串长度必须在5到9个字符之间。

    抛开这些建议不谈,如果您必须使用字符数组,并且希望使用循环来检查验证数组中的单个字符(我当然不建议这样做),那么目标应该是减少所涉及的数组元素的数量,从而减少总的迭代次数。

    • 你的 $allowedChars array_unique() 或者类似的技术。
    • str_split($input) 将运行生成具有重复元素的数组的机会。例如,如果 $input="Test Test Test Test"; str_split() 将有19个元素,其中14个将需要冗余的验证检查。
    • 你也许可以从中消除冗余 count_chars($input,3) str\u split() 或者你可以打电话 数组\唯一()
        5
  •  0
  •   bob-the-destroyer    14 年前

    preg_match() 以及其他PCRE函数来处理此问题。

    strcspn() 要做的事。。。

    $check = "abcde.... '; // fill in the rest of the characters
    $test = "Test";
    echo ((strcspn($test, $check) === strlen($test)) ? "Sigh, not found..." : 'Yep, found.');