代码:
$searchText = '3423, 2453, 3245 , 2425, 6765';
$numbers = str_replace(", ", ",", $searchText);
$code = explode(",", $numbers);
if ( (preg_match("/[^0-9]/i"), $code) || (strlen($code) != 4) ) {
$searchingError= 'Can not cantain string and more than 4 digists number!';
echo '<script type="text/javascript">';
echo "alert('" . $searchingError . "')";
echo "</script>";
}
function validate ($a) {
if (ctype_digit($a) && (strlen($a) == 4)) {
return "'$a'" ;
} else {
//$searchingError= 'Can not cantain string and more than 4 digists number!';
//echo '<script type="text/javascript">';
//echo "alert('" . $searchingError . "')";
//echo "</script>";
}
}
$parsed = array_map( "validate",$code);
print_r($parsed);
$code = '(' . preg_replace('/\,+/', ',',implode(',', $parsed)) . ')';
echo '<br />' . $code;
在这段代码中,有没有办法识别$ searchText只有4位数字或者它包含字符串等。如果是这样,我想回显错误信息。
感谢您提出任何意见。
答案 0 :(得分:2)
使用is_int
检查$ code是否为文本,使用strlen();
检查每个数字的长度
在if语句中:
if (is_int($code)) {
if (strlen($num1) = 4 && strlen($num2) ...) {
//code here
}
else
echo "Error.";
}
else
echo "The search is text";
答案 1 :(得分:0)
这将验证它们只是数字而且只有4个字符......
//is not digits or //is not 4 characters in length
if ( (preg_match("/[^0-9]/i"), $code) || (strlen($code) != 4) ) {alert error...}
答案 2 :(得分:0)
GOT IT!
<?php
$a = "4444 , 111X , 565656, 4444";
$a = str_replace(" ", "", $a);
$b = explode(",",$a);
function validate($v){
if ((strlen($v)!=4)||(preg_match("/[^0-9]/i", $v))) { echo 'error<br/>'; }else{ echo 'success<br/>'; };
}
array_filter($b,"validate");
echo 'complete';
?>