2012-01-27 2 views
1

[<,{ or ],>,}로 둘러싸인뿐만 아니라 경우 :분할이 나는이 같은 문자열이

traceroute <ip-address|dns-name> [ttl <ttl>] [wait <milli-seconds>] [no-dns] [source <ip-address>] [tos <type-of-service>] {router <router-instance>] | all} 

이 같은 배열을 만들 싶습니다

$params = array(
     <ip-address|dns-name> 
     [ttl <ttl>] 
     [wait <milli-seconds] 
     [no-dns] 
     [source <ip-address>] 
     [tos <tos>] 
     {router <router-instance>] | all} 
); 

해야 하는가를 preg_split('/someregex/', $mystring)을 사용하고 있습니까? 더 좋은 해결책이 있습니까?

답변

1

당신은 preg_match_all 등을 사용할 수 있습니다.

1

예, preg_split은 의미가 있으며 아마도 가장 효율적인 방법 일 것입니다.

시도 :

preg_split('/[\{\[<](.*?)[>\]\}]/', $mystring); 

아니면 오히려 분할 이상 일치 할 경우, 당신이 시도 할 수 있습니다 :

$matches=array(); 
preg_match('/[\{\[<](.*?)[>\]\}]/',$mystring,$matches); 
print_r($matches); 

난 당신이 노력하고 있음을 놓친 업데이트 토큰을 가져오고 토큰의 내용은 가져 오지 않습니다. I 생각하면 당신은 preg_match를 사용해야 할 것입니다. 좋은 시작이처럼 뭔가를보십시오 :

$matches = array(); 
preg_match_all('/(\{.*?[\}])|(\[.*?\])|(<.*?>)/', $mystring,$matches); 
var_dump($matches); 

내가 얻을 다음 $matches 배열에서 결과를

preg_match_all("/\\[[^]]*]|<[^>]*>|{[^}]*}/", $str, $matches); 

얻을 :

Array 
(
[0] => Array 
    (
     [0] => <ip-address|dns-name> 
     [1] => [ttl <ttl>] 
     [2] => [wait <milli-seconds>] 
     [3] => [no-dns] 
     [4] => [source <ip-address>] 
     [5] => [tos <type-of-service>] 
     [6] => {router <router-instance>] | all} 
    ) 
+0

감사합니다, 그러나에이 정규식 분할은 [,], ... 나는 두 단어가 이들에 의해 둘러싸여하지 않는 경우에만 공백에 분할하고 싶습니다 chars. – Franquis

+0

@Franquis가이 작업을 수행합니까? –

2

부정적인 해결책을 사용하십시오. 이것은 <에 대한 부정적인 선견자를 사용합니다. 즉, 공백 문자보다 앞에 <을 발견하면 분할되지 않습니다.

$regex='/\s(?!<)/'; 
$mystring='traceroute <192.168.1.1> [ttl <120>] [wait <1500>] [no-dns] [source <192.168.1.11>] [tos <service>] {router <instance>] | all}'; 

$array=array(); 

$array = preg_split($regex, $mystring); 

var_dump($array); 

그리고 내 출력은

array 
    0 => string 'traceroute <192.168.1.1>' (length=24) 
    1 => string '[ttl <120>]' (length=11) 
    2 => string '[wait <1500>]' (length=13) 
    3 => string '[no-dns]' (length=8) 
    4 => string '[source <192.168.1.11>]' (length=23) 
    5 => string '[tos <service>]' (length=15) 
    6 => string '{router <instance>]' (length=19) 
    7 => string '|' (length=1) 
    8 => string 'all}' (length=4)