我有这个字符串(245)“- 当前地图 = VILLA - 当前任务 = VEGAS JUNKYARD、VILLA、PRESIDIO、KILL HOUSE、街道、三个王国赌场; - 可用任务 = TRAINYARD、IMPORT/EXPORT、MURDERTOWN、CQB 培训、炼油厂, 会议中心, 剧院;"
当前地图始终是一个值,当前任务和可用任务具有可变数量的值。
我想解析字符串,以便我有一个如下所示的数组:
Array ([Current Map] => VILLA [Current Missions] => Array ([0] => VEGAS JUNKYARD [1] => VILLA [2] => PRESIDIO [3] => KILL HOUSE [4] => STREETS [5] => THREE KINGDOMS CASINO) [Availible Missions] => Array ([0] => TRAINYARD [1] => IMPORT/EXPORT [2] => MURDERTOWN [3] => CQB TRAINING [4] => OIL REFINERY [5] => CONVENTION CENTER [6] => THEATER))
工作原理:它将 3 个主要部分(当前地图、当前任务、可用任务)分开
什么不起作用:将“当前任务”和“可用任务”的多个值分隔到一个数组中。
错误(或者我只是愚蠢):注意“可用任务”之前的分号
$search_strs_maps = array('Current Map = ', '- Current Missions = ', '; - Available Missions = ', ';');
如果我把分号放在那里,即使我很确定分号在字符串中,它也找不到任何东西。
我提出这个的原因是,当我将分号放在“可用任务”之前时,我无法弄清楚为什么它没有找到任何东西,这让我发疯。此外,我还可以对代码进行第二次观察,并就如何使它变得更好提供一些建议。谢谢你的帮助!
这是我到目前为止所写的。
<?php
$str_map = '- Current Map = VILLA - Current Missions = VEGAS JUNKYARD, VILLA, PRESIDIO, KILL HOUSE, STREETS, THREE KINGDOMS CASINO; - Available Missions = TRAINYARD, IMPORT/EXPORT, MURDERTOWN, CQB TRAINING, OIL REFINERY, CONVENTION CENTER, THEATER;';
$search_strs_maps = array('Current Map = ', '- Current Missions = ', '- Available Missions = ', ';');
for ($i=0; $i<3; $i++){
$str_map = trim ($str_map);
output($str_map, 'Complete String');
//Cut of the beginning : "- Current Map = "
$start_pos = str_pos_last ($str_map, $search_strs_maps[$i]);
output($start_pos, 'Starting position');
$str_map = substr($str_map, $start_pos);
output($str_map, 'String after first cut:');
//Cut the remaining part to "Current Missions ="
$end_pos = strpos ($str_map, $search_strs_maps[$i+1]);
output($end_pos, 'End position');
//Save the new string without for example "VILLA"
$ergebnis = substr($str_map, 0, $end_pos);
$ergebnis = trim ($ergebnis);
output($ergebnis, 'Finished result');
$str_map = substr($str_map, $end_pos);
echo '<hr>';
if ($i==0){
$arr_return_strs['current_map'] = $ergebnis;
}else{ //arrays
//stupid semicolon that doesnt get cut of
$ergebnis = str_replace ($str_map, ';', '');
$arr_maps_temp = array();
//count the number of commas, if there is one comma that means there are 2 words, there is no comma at the end
$map_count = substr_count ($ergebnis, ',')+1;
for ($ii=0;$ii<$map_count;$ii++){
echo '<hr';
//cut at first comma
$result_pos = strpos($str_map, ',');
//save
$result_map = substr($str_map, 0, $result_pos);
//cut of the result+comma
$ergebnis = substr ($ergebnis, $result_pos);
output($result_map, 'Result is:');
}
}
}
echo '<hr><hr><hr>';
print_r ($arr_return_strs);
function str_pos_last ($input_str, $search_str, $offset=0){
//this function returns the endposition of a string we search for, strpos returns the beginning...
$str_begin = strpos ($input_str, $search_str);
$str_end = $str_begin + strlen($search_str);
return $str_end;
}
function output ($var, $desc){
echo $desc.'<br>';
var_dump ($var);
echo '<hr>';
}
?>