2017-07-26 193 views
0

我有一個字符串,如下所示:爆炸字符串

 $str = "am_customers.customer_key,am_customers.add_dt,CONCAT(am_customers.first_name,'',am_customers.last_name) as 
      name,am_customers.cell_phone,am_customers.crm_phase_key, am_customers.source,am_customers.location_key,am_customers.hub_key, 
      am_customers.crm_priority,am_customers.update_dt"; 

我想explod用逗號的字符串。但問題是打開和關閉括號,當我嘗試expload用逗號的字符串,我會得到的結果類似如下

  Array 
     (
      [0] => am_customers.customer_key 
      [1] => am_customers.add_dt 
      [2] => CONCAT(am_customers.first_name 
      [3] => '' 
      [4] => am_customers.last_name) as name 
      [5] => am_customers.cell_phone 
      [6] => am_customers.crm_phase_key 
      [7] => am_customers.source 
      [8] => am_customers.location_key 
      [9] => am_customers.hub_key 
      [10] => am_customers.crm_priority 
      [11] => am_customers.update_dt 
     ) 

但我想要的結果類似如下:

 Array 
    (
     [0] => am_customers.customer_key 
     [1] => am_customers.add_dt 
     [2] => CONCAT(am_customers.first_name,'',am_customers.last_name) as name 
     [3] => am_customers.last_name) as name 
     [4] => am_customers.cell_phone 
     [5] => am_customers.crm_phase_key 
     [6] => am_customers.source 
     [7] => am_customers.location_key 
     [8] => am_customers.hub_key 
     [9] => am_customers.crm_priority 
     [10] => am_customers.update_dt 
    ) 

有沒有辦法像我想要的那樣做到這一點?

謝謝。

+0

使preg_split。 – Devon

回答

1

通過@Devon由註釋啓發你可以用preg_match_all實現這一目標:

preg_match_all('/[^C\(,]*(?:(?:Cf\.|C(?!f)|\([^)]*\))[^C\(,]*)*/', $str, $matches);

正則表達式來源:http://www.perlmonks.org/?node_id=907316

我只是測試這個代碼,它似乎做你所要求的:

$str = "am_customers.customer_key,am_customers.add_dt,CONCAT(am_customers.first_name,'',am_customers.last_name) as 
      name,am_customers.cell_phone,am_customers.crm_phase_key, am_customers.source,am_customers.location_key,am_customers.hub_key, 
      am_customers.crm_priority,am_customers.update_dt"; 

$matches = []; 
preg_match_all('/[^C\(,]*(?:(?:Cf\.|C(?!f)|\([^)]*\))[^C\(,]*)*/', $str, $matches); 

/* 
* Trims each match, removes empty string matches, and resets array keys. 
* 
* Source: http://php.net/manual/en/function.array-filter.php#111091 
*/ 
$clean = array_map('trim', $matches[0]); 
$clean = array_filter($clean, 'strlen'); 
$clean = array_values($clean); 

var_dump($clean); 

文檔

array_filterhttp://php.net/array_filter

array_maphttp://php.net/array_map

array_valueshttp://php.net/array_values

preg_match_all:使用正則表達式只包括括號以外逗號http://php.net/preg_match_all

+0

Hi @ rideron89, preg_match_all('/ [^ C \(,] *(?:(?: Cf \。| C(?!f)| \([^)] * \))[^ C \( ,] *)* /',$ str,$ matches); 上面的代碼給了我一個錯誤,我認爲有些東西是錯誤的 – Punam

+0

非常感謝,它爲我工作。 – Punam