创建将字符串解析为数组PHP的函数

时间:2017-01-27 00:01:21

标签: php regex drupal preg-match

我想创建一个将字符串解析为数组的php函数(我发现这不容易),字符串变化很多,我不知道如何以适合下面任何字符串的方式执行此操作($文本1,...,$ 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;
    }


    ?>

1 个答案:

答案 0 :(得分:0)

我不太确定,但你可以测试一下:

修改

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;
}