如何检查输入是否包含数组之一


How to check if input contains one of array?

我有一个这样的输入:

<input name='postImg' type='text'><?php if(isset($error)){ echo $_POST['postImg'];}?></input>

我希望PHP检查输入文本是否包含:.png或.jpeg或.gif等。以确保它是一个图像。但它必须是输入名称(所以没有上传)。

我怎样才能做到最好?

您可以使用正则表达式。这将检查扩展是否正确;匹配字符串的末尾(.png、.jpeg、.jpg、.gif)

if( preg_match("/'.(png|jpeg|jpg|gif)$/", $_POST['postImg']) ) {
   //Yep.
}

示例:https://eval.in/208018

编辑

if( strlen($postImg) > 0 AND preg_match("/'.(png|jpeg|jpg|gif)$/", $postImg) == FALSE) {
   $error[] = 'Wrong image format.';
}

尝试:

if(strpos($_POST['postImg'], '.png') || strpos($_POST['postImg'], '.jpeg') || strpos($_POST['postImg'], '.gif')) {
    echo 'It exists';
}