[英]How to validate the format of a string?
基本上,我有一個變量,是通過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
如果可能,我需要使用布爾變量驗證它,如果它與格式匹配,則返回true或false。 這些字符串可以包含任何內容,例如字母,數字,特殊字符等。
每行總會有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";
}
}
非常感謝所有幫助。
提前致謝!
聽起來像正則表達式可以完成這項工作:
$match_ok = preg_match('/^([^,]+,){4}[^,]+$/', $test_string);
如果要允許[string]
為空,則可以將所有+
更改為*
。
說明:第一個^
匹配行的開頭,然后是一個或多個非逗號字符,后跟一個逗號。 該序列必須存在4次,並且必須緊跟另一個不以逗號結尾的字符串。 $
與行尾匹配。
如果要匹配while多行字符串,可以使用:
$match_ok = preg_match('/^(([^,]+,){4}[^,]+\n){3}$/', $test_string);
(因為preg_match
默認在多行模式下工作)
編輯2:您甚至可以通過分別處理最后一行,使正則表達式與不以換行符結尾的字符串匹配,就像使用cols一樣:
$match_ok = preg_match('/^(([^,]+,){4}[^,]+\n){2}([^,]+,){4}[^,]+$/', $test_string);
試試這個簡單的方法,可能有很多其他解決方案
<?php
$test_string = "question1,answer1,answer2,answer3,answer4";
$newarray=explode(',',$test_string);
if(count($newarray)=='5'){
your code......;
}
?>
- - - - - - - - - - 真假 - - - - - - -
<?php
$test_string = "questionAsdAD1###,234234,answer2,answer3,answer4";
function ToCheckMyStrung($test_string){
$newarray=explode(',',$test_string);
if(count($newarray)=='5'){
return true;
} else {
return false;
}
}
?>
在foreach中使用
implode(',',$row); for proper formatting.
您可以在創建字符串變量時執行此操作,
$count=1;
$trace=array();
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";
if($row[1]=="" || $row[2]=="" || $row[3]=="" || $row[4]=="" || $row[5]=="")
{
$trace[]=$count;
}
$count++;
}
}
而不僅僅是在需要時使用$ trace數組。
正則表達式將幫助您:
$test_string = "Some,string,you,want,to,test";
if(preg_match('@^([a-zA-Z0-9]+\,)+([a-zA-Z0-9])+$@', $test_string)) {
echo 'All ok';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.