我有一些PHP代码接受来自HTML表单的上传文件,然后使用正则表达式查找特定行(在下面的例子中,那些带有“Number”后跟一个整数的行)。
正则表达式匹配我想要的整数,但当然它们在$ matches中作为字符串返回。我需要检查整数是否介于0和9之间,但无论我尝试什么,我都无法做到这一点。
使用intval()或(int)首先将匹配转换为整数,即使给定的字符串仅包含整数,也始终返回0。并使用in_array将整数与0-9的数组进行比较,因为字符串总是因某种原因返回false。这是故障代码...
$myFile = file($myFileTmp, FILE_IGNORE_NEW_LINES);
$numLines = count($myFile) - 1;
$matches = array();
$nums = array('0','1','2','3','4','5','6','7','8','9');
for ($i=0; $i < $numLines; $i++) {
$line = trim($myFile[$i]);
$numberMatch = preg_match('/Number(.*)/', $line, $matches);
if ($numberMatch == 1 and ctype_space($matches[1]) == False) { // works up to here
$number = trim($matches[1]); // string containing an integer only
echo(intval($number)); // conversion doesn't work - returns 0 regardless
if (in_array($number,$nums)) { // searching in array doesn't work - returns FALSE regardless
$number = "0" . $number;
}
}
}
我尝试过类型检查,双引号,单引号,修剪空格,UTF8编码......还有什么可能呢?我将完全放弃这个应用程序,请救救我。
答案 0 :(得分:1)
使用&#39; ===&#39;例如,等等
if 1 == '1' then true;
if 1 === '1' false;
if 1 == true then true;
if 1 === true then false
你可以显示文件吗?
答案 1 :(得分:0)
您在问题中写道,您正在使用正则表达式来查找术语&#34; Number&#34;后跟一个数字(0-9)。
它的正则表达式是:
/Number(\d)/
它将在匹配组1中包含您正在寻找的数字(数字)。
您使用的模式:
/Number(.*)/
可以在第一个匹配组中包含任何内容(但换行符)。它显然匹配太多了。然后,你有一个过于追溯过滤的问题。
通常情况下,首先看起来尽可能精确,而不是在事后发出太多噪音。