我想要创建一个php函数,它将一个字符串解析成一个数组(我发现这并不容易),这些字符串变化很大,我不知道如何对下面的任何字符串正确地工作($text1,.,$textn):
    <?php
    $text1 ='balance_check!en:[ussd]Your balance is $balance $currency;ru:[ussd]Vash balans $balance $currency;';
    //function outputs: $text_array = array ('type'=>'ussd','en'=>'Your balance is', 'ru'=>'Vash balans');
    $text2 = 'voicemail!:[redirect]*44*2*$number';
    //function outputs: $text_array = array('type'=>'redirect');
    $text3='callerid!en:success=[ussd]$callerid is your Caller-ID/error=[ussd]Bad caller-ID number;';
    //function outputs: $text_array = array('type'=>'ussd','en'=>array('success'=>'is your Caller-ID', 'error'=>'Bad caller-ID number'));
    $text4 ='voucher_recharge!en:success=[sms]Your balance is $balance $currency. Voucher recharged successfully';
    //function outputs: $text_array = array('type'=>'sms','en'=>array('success'=>array('Your balance is','Voucher recharged successfully'),),);
//parse into an array
function multiexplode($text) {
        //parse $text into array
        // return  $text_array;
    }
    ?>发布于 2017-01-27 16:18:22
我不太确定,但你可以测试一下:
编辑
function transform($string) {
  $string = preg_replace('/\$[a-zA-Z0-9]+/i', '', $string); // remove $words pattern
  $text = end(explode('!',$string,  2)); // get part of string targeted
  preg_match_all('#([a-z]{2})?\:?([a-z]+)?\=?\[([a-zA-Z]+)\]#iU', $text, $matches); // Find all parts needed to build array
  $output = array();
  $text = str_replace($matches[0], '#SPLITME#', $text);
  $sentences = explode( '#SPLITME#', $text);
  foreach ($sentences as $k => $v){
    if(empty($v) || $v == '') unset($sentences[$k]);
  }
  $sentences = array_values($sentences);
  $lang_memory = null;
  foreach ($matches[1] as $key => $lang){
    $output['type'] = $matches[3][0]; // get type 
    if(!empty($lang) ){
      if(isset($matches[2][$key]) && !empty($matches[2][$key])){
        // success or error key found
        $output[$lang][$matches[2][$key]] = $sentences[$key];
        $lang_memory = $lang;
      }else{
        $output[$lang] = $sentences[$key]; // no success of error key found
      }
    }else if($lang_memory != null){
      if(isset($matches[2][$key]) && !empty($matches[2][$key])){
        $output[$lang_memory][$matches[2][$key]] = $sentences[$key];
      }
    }
  }
  return $output;
}https://stackoverflow.com/questions/41885152
复制相似问题