【发布时间】:2013-08-23 12:42:13
【问题描述】:
基本上,我有一个通过 foreach 循环从多维数组构建的变量。
我需要以某种方式验证它的格式,虽然我不确定如何去做,因为我还是个 PHP 新手。
这就是我的字符串的样子:
question1,answer1,answer2,answer3,answer4
question2,answer1,answer2,answer3,answer4
question3,answer1,answer2,answer3,answer4
我需要验证确切的格式,即:
string[comma]string[comma]string[comma]string[comma]string
string[comma]string[comma]string[comma]string[comma]string
string[comma]string[comma]string[comma]string[comma]string
如果可能的话,我需要用一个布尔变量来验证它,如果它与格式匹配则返回真或假。这些字符串可以包含任何内容,例如字母、数字、特殊字符等。
每行总是有 5 个字符串和 4 个逗号,不会多也不会少。
如果需要,这是构建多维数组然后将其转换为字符串的代码。它正在抓取上传的 CSV 文件,将其转换为多维数组,然后构建字符串。如您所见,我的数组是从 1 而不是 0 开始的,没有必要解释原因,因为那是题外话。
$csv_array = array(array());
if (!empty($_FILES['upload_csv']['tmp_name']))
{
$file = fopen($_FILES['upload_csv']['tmp_name'], 'r');
}
if($file)
{
while (($line = fgetcsv($file)) !== FALSE)
{
$csv_array[] = array_combine(range(1, count($line)), array_values($line));
}
fclose($file);
}
if(!empty($csv_array[1]))
{
foreach (array_slice($csv_array,1) as $row)
{
$all_questions = $all_questions . $row[1] . ",";
$all_questions = $all_questions . $row[2] . ",";
$all_questions = $all_questions . $row[3] . ",";
$all_questions = $all_questions . $row[4] . ",";
$all_questions = $all_questions . $row[5];
$all_questions = $all_questions . "\n";
}
}
非常感谢所有帮助。
提前致谢!
【问题讨论】:
-
使用
explode(),并计算结果数组有多少项?但这只有在字符串中没有逗号的情况下才有效。 -
if (count($line) == 5) -
@andrewsi OP 已经在使用
fgetcsv(),所以他不会有这个问题。
标签: php validation