2017-02-22 3 views
0

I는 다음과 같습니다 기존 배열의 값이에 의해 괄호 사이에 텍스트의 배열을 만들기 : 내가이 빠져하려고하면 다음과 같다 배열입니다쉼표로 구분 된 값

Product One (Amount: 199.99 USD, Select Option: Option One, Product One (CRM): 1) 

을 : 나는 무엇을 시도했다

Product One 
    Amount: 199.99 USD 
    Select Option: Option One 
    Product One (CRM): 1 

은 다음과 같습니다

$product_arr = json_decode($product_details[0]); 
$prod_arr_add = preg_split('/[\,(]+/', $product_arr[0]); 
print_r ($prod_arr_add); 

:

Array 
(
    [0] => Product One 
    [1] => Amount: 199.99 USD 
    [2] => Select Option: Option One 
    [3] => Product One 
    [4] => CRM): 1) 
) 

다른 시도를 통해 시도한 결과가 유사하게 원하는 결과를 얻지 못했습니다.

어떻게 텍스트 문자열을 배열로 분할 할 수 있습니까?

+0

** 위의 사용자 삭제 코멘트. 건의했다 explode() - 좋아, 그것을 시도했다. '배열 ( [0] => 제품 하나 (금액 : 199.99 USD [1] => 선택 옵션 : 옵션 1 [2] => 제품 하나 (CRM) : 1) 이것은 내가 무엇을 얻을 )' 어떻게 두 개의 불량 괄호를 제거 할 수 있습니까? – jarmerson

+0

패턴이 모든 제품에 적용되는 경우 [this one] (https://regex101.com/r/aRmO1k/1)과 같은 정규식을 사용해보십시오. – sevavietl

답변

0

테스트 할 단 하나의 샘플 문자열로, 나는 몇 가지 가정을하고 정규식 효율을 희생했습니다. 이 솔루션을 강화해야 할 경우 의견을 말하고 수정하십시오.

$regex="/^(.+?)\s\((.*?),\s(.*?),\s(.*)\)$/"; 
$string="Product One (Amount: 199.99 USD, Select Option: Option One, Product One (CRM): 1)"; 

if(preg_match($regex,$string,$matches)){ 
    $prod_arr_add=array_slice($matches,1); // remove first element from the array (fullmatch) 
    echo "<pre>"; 
     var_export($prod_arr_add); 
    echo "</pre>"; 
}else{ 
    echo "no match"; 
} 

출력 :

array (
    0 => 'Product One', 
    1 => 'Amount: 199.99 USD', 
    2 => 'Select Option: Option One', 
    3 => 'Product One (CRM): 1' 
) 

정규식 :

^(.+?)\s\( #Capture everything from the start to a space followed by a opening parenthesis 
(.*?),\s #Capture everything before a comma followed by a space 
(.*?),\s #Capture everything before a comma followed by a space 
(.*)\)$  #Capture everything before a closing parenthesis at the end of the string 
+0

거기서 사용한 정규식을 설명해 주시겠습니까? – jarmerson

+0

@jarmerson 답변이 수정되었습니다. 이 문제가 만족 스럽다면 녹색 틱 (green tick)을 주시겠습니까? – mickmackusa

+0

굉장합니다. 저는 현재 별도의 프로젝트를 진행하고 있습니다 만, 이번 주에 계속 될 예정이며 절대적으로 시도하고 다시 연락 할 것입니다. – jarmerson