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

Sco*_*ott 5 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...";}
Run Code Online (Sandbox Code Playgroud)

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

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

Ste*_*hen 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;
Run Code Online (Sandbox Code Playgroud)