在我玩遊戲的網站上工作。在這個頁面上,用戶可以上傳描述一件設備的文本塊,並希望我可以通過它解析創建一個對象並將其上傳到MySQL。下面是一個例子塊:PHP中的嵌套開關
Item: an ethereal bracelet
Key words: geq grey_man man ethereal bracelet geq_Guxx
Type: treasure
Level: 50
Extra flags: rot-death no-transfer
Weight: 2
Value: 0
Affects: spell-resistance by 5.
Affects: dexterity by 1.
Affects: strength by 1.
Affects: intelligence by 1.
Affects: wisdom by 1.
Affects: hitroll by 5.
Affects: constitution by 1.
Affects: hp by 50.
Affects: damroll by 10.
這裏是在我的設備類中的函數:
public function create_eq_from_text($text) {
$text = trim($_POST['item']);
$text = explode("\n", $text);
foreach($text as $line) {
switch($line) {
case strstr($line, 'Item:'):
$this->name = trim(str_replace('Item:', '', $line));
break;
case strstr($line, 'Key words:'):
$line = trim(str_replace('Key words:', '', $line));
$this->key_words = $line;
break;
case strstr($line, 'Type:'):
$line = trim(str_replace('Type:', '', $line));
$this->type = $line;
break;
case strstr($line, 'Level:'):
$line = trim(str_replace('Level:', '', $line));
$this->level = intval($line);
break;
case strstr($line, 'Extra flags:'):
$line = trim(str_replace('Extra flags:', '', $line));
$this->extra_flags = $line;
break;
case strstr($line, 'Weight:'):
$line = trim(str_replace('Weight:', '', $line));
$this->weight = intval($line);
break;
case strstr($line, 'Value:'):
$line = trim(str_replace('Value:', '', $line));
$this->value = intval($line);
break;
case strstr($line, 'physical attacks'):
$this->p_ac = get_number($line);
break;
case strstr($line, 'magic attacks'):
$this->m_ac = get_number($line);
break;
case strstr($line, 'spell-resistance'):
$this->saves = get_number($line);
break;
case strstr($line, 'dexterity by'):
$this->dex = get_number($line);
break;
case strstr($line, 'strength by'):
$this->str = get_number($line);
break;
case strstr($line, 'intelligence by'):
$this->intel = get_number($line);
break;
case strstr($line, 'wisdom by'):
$this->wis = get_number($line);
break;
case strstr($line, 'constitution by'):
$this->con = get_number($line);
break;
case strstr($line, 'damroll by'):
$this->dam = get_number($line);
break;
case strstr($line, 'hitroll by'):
$this->hit = get_number($line);
break;
case strstr($line, 'hp by'):
$this->hp = get_number($line);
break;
case strstr($line, 'mana by'):
$this->mana = get_number($line);
break;
case strstr($line, 'Damage is'):
$line = trim(str_replace('Damage is', '', $line));
$line = str_replace('.', '', $line);
$this->weapon_damage = $line;
break;
}
}
}
這裏是窗體代碼:
if(isset($_POST['submit']) && !empty($_POST['item'])) {
$item = new Equipment;
$item->create_eq_from_text($item);
print_r($item);
}
出於某種原因,唯一的開關捕捉的是strstr('Item:')。首先,我認爲轉換中的突破已經脫離了習慣,但我已經排除了這一點。任何人都可以將我指向正確的方向嗎?
對於要評估的案例,它必須匹配傳入開關的參數。 – 2012-07-25 04:00:22
@Matthew Scragg strstr()將返回false,如果沒有匹配,奇怪的是它可以用於設置$ this->名稱,但不會觸發其他任何事情。 – 2012-07-25 04:03:29
您必須重新構建......用switch語句,您基本上是在說「這裏有一個$ line的值,與所有這些case值進行比較,並在匹配的任何地方運行」。自然$ line!= strstr($ line,'Item:') – Mahn 2012-07-25 04:06:04