2012-02-21 2 views
1

첫 번째 질문은 매우 빠르게 답변되었습니다. 여기 쉼표로 구분 된 다른 필드에서 공백으로 구분 된 필드를 가져옵니다. (루프?)

다른이 너무 midname있는 동안 한 두 값 (이름, 성)가,

$str= "name1 surname2, name2 midname2 surname2"; 

일을 더 명확하게하기 위해이 두 사람이 .. 주어진 문자열이 문제입니다. 그래서 어떤 이름이 어느 사람에게 속하는지 알면서 모든 것을 분리시켜야합니다.

foreach ($persons as person){ 
    if(person has midname){ 
     $value1 ="name"; $value2= "midname"; $value3="surname"} 
    else 
    $value1="name"; $value2="surname" 
    } 

답변

1
$str = str_replace(',', '', $str); 
$arr = explode(' ', $str); 
1

만약 당신이 preg_split 사용할 수있는 구분 기호로 공백이나 쉼표 중 하나를 사용하여 문자열을 분할 수행 할 작업 :

$str = "field1 field2 field3, field4 field5, field6"; 

$v = preg_split("/[\s,]+/", $str); 

var_dump($v); 

을 그리고 당신이 얻을 것이다 :

array(6) { 
    [0]=> 
    string(6) "field1" 
    [1]=> 
    string(6) "field2" 
    [2]=> 
    string(6) "field3" 
    [3]=> 
    string(6) "field4" 
    [4]=> 
    string(6) "field5" 
    [5]=> 
    string(6) "field6" 
} 
0
<?php 
    $str = "field1 field2 field3, field4 field5, field6 field7 , field8"; 

    // even works on more than one space or a comma surrounded by spaces. 
    $v = preg_split("~\s*,\s*|\s+~", $str); 

    var_dump($v); 
?> 

출력

array 
    0 => string 'field1' (length=6) 
    1 => string 'field2' (length=6) 
    2 => string 'field3' (length=6) 
    3 => string 'field4' (length=6) 
    4 => string 'field5' (length=6) 
    5 => string 'field6' (length=6) 
,515,
1

난 .. 일반적인 세퍼레이터()를 분해 한 후 처음의 separater charater을 정상화

# replace spaces with commas: 
$str = str_replace(' ', ',', $str); 
# replace the 'doubled commas' with single commas: 
$str = str_replace(',,', ',', $str); 
# now you have normalized input: 
print_r(explode(',', $str));