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

时间:2010-07-20 01:43:55

标签: php arrays string

我基本上需要一个函数来检查字符串的字符(每个字符)是否在数组中。

到目前为止,我的代码无法运行,但无论如何,

$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...";}

我希望它说'是的,找到了'。如果在$allowedChars中找到$ input中的一个字母。很简单吧?好吧,这不起作用,我还没有找到一个函数来搜索字符串的单个字符以获取数组中的值。

顺便说一下,我希望它只是那些数组的值,我不是在寻找花哨的html_strip_entities或者它是什么,我想使用那个确切的数组来表示允许的字符。

5 个答案:

答案 0 :(得分:6)

你真的应该研究一下正则表达式和preg_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;

答案 1 :(得分:4)

你是否熟悉正则表达式?除非我在这里遗漏了一些东西,否则这是做你正在做的事情的更被接受的方式。

看看preg_match():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 :(";

对正则表达式的一点解释:'^'匹配字符串的开头,'[a-zA-Z0-9 @ ._ + - ]'部分表示“此集合中的任何字符”,' *'在它之后表示“最后一个零或更多”,最后在结尾处的'$'匹配字符串的结尾。

答案 2 :(得分:1)

一种不同的方法:

$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);
}

答案 3 :(得分:1)

使用字符串函数最有效地验证字符串中的字符。
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。&#34;任何单词字符&#34; - &gt; a shorthand character class)是一种简单易懂的方式:[a-zA-Z0-9_]
  • . dot character失去了&#34;匹配任何东西(差不多)&#34;当它写在一个字符类中时,它意味着变成文字。不需要逃避斜线。
  • character class内的连字符可以在没有转义斜杠(\-)的情况下编写,只要它位于字符类的开头或结尾即可。如果连字符不在开头/结尾且未被转义,则会在其两侧的字符之间创建一系列字符。
    无论喜欢与否,[.-z]都不匹配连字符符号,因为它不存在&#34;之间&#34; ascii table上的点字符和小写字母z。
  • 字符类后面的*是&#34; quantifier&#34;。星号表示&#34; 0或更多&#34;前面的字符类。在这种情况下,这意味着preg_match()将允许空字符串。如果你想拒绝一个空字符串,你可以使用+,这意味着&#34; 1或更多&#34;前面的字符类。最后,通过在卷曲括号表达式中使用数字或数字,您可以更加具体地了解字符串长度。
    • {8}表示字符串必须长度为8个字符。
    • {4,}表示字符串长度必须至少为4个字符。
    • {,10}表示字符串长度必须介于0到10之间。
    • {5,9}表示字符串长度必须介于5到9个字符之间。

除了所有这些建议之外,如果你绝对必须使用你的字符数组并且你想使用循环来检查你的验证数组中的单个字符(我当然不推荐它),那么目标应该是是减少所涉及的数组元素的数量,以减少总迭代次数。

  • 您的$allowedChars数组包含多个包含空格字符的元素,但只需要一个。您应该使用array_unique()或类似技术准备阵列。
  • str_split($input)将有机会生成包含重复元素的数组。例如,如果$input="Test Test Test Test";,则str_split()生成的数组将包含19个元素,其中14个元素将需要进行冗余验证检查。
  • 您可以通过调用str_split()并将其提供给count_chars($input,3)来消除str_split()中的冗余,或者在执行迭代之前,您可以调用str_split()然后调用array_unique()过程

答案 4 :(得分:0)

因为您只是验证字符串,请参阅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.');