我有一个从输入字段生成的字符串,我想检查前两个字符并查看是否在数组中找到它们。如果是,我希望显示一条消息。
谁能解释为什么这不起作用?
$i = strtoupper($_POST['postcode']);
$ep = array("AB", "BT", "GY", "HS", "IM", "IV", "JE", "PH", "KW");
if (isset($i)) {
if(substr($i, 0, 2) === in_array($i, $ep)) {
echo "Sorry we don't deliver to your postcode";
}
}
最佳答案
你误解了 in_array
的工作原理,检查 manual了解更多详情。
以下代码是检查给定邮政编码是否有效的改进方法
<?php
/**
* Check if the given post code is valid
* @param string $postcode
* @return boolean
*/
function is_valid_postcode( $postcode = '' )
{
$ep = array("AB", "BT", "GY", "HS", "IM", "IV", "JE", "PH", "KW");
$postcode = strtoupper( $postcode );
return in_array( $postcode , $ep );
}
if( isset( $_POST['postcode'] ) ){
// Remove unwanted spaces if they're there
$postcode = trim( $_POST['postcode'] );
// Extract only the first two caracters
$postcode = substr($postcode, 0, 2 );
// Check if the submitted post code is valid
if( !is_valid_postcode( $postcode ) ){
echo "Sorry we don't deliver to your postcode";
}
}
关于php - substr 前两个字母在数组中匹配不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48805452/