2015-01-10 2 views
3

나는 IP 주소와 포트 목록이 길다.PHP preg이 문자열을 일치시키는 방법은 무엇입니까?

preg_match_all('/connect=;;(.+?);;/', $long, $ip); 
      $ip = $ip[1][0]; 
      print_r($ip); 

이가 완벽하게 작동 : 나는 아무런 문제가 사용하는 글로벌 IP 주소와 일치하지 레그 있었다

/connect=;;41.26.162.36;;192.168.0.100;;8081;; 
/connect=;;98.250.16.76;;192.168.0.24;;8080;; 
/connect=;;216.152.60.12;;192.168.1.103;;8090;; 
/connect=;;91.11.65.110;;192.168.1.3;;8081;; 

:이 비슷합니다 목록에서 포트 번호와 일치 레그하기 위해 노력하고있어 나,하지만 난 라인의 끝에 앉는 포트를 preg하는 방법을 알아낼 수 없습니다.

+0

는 '이 아닌 숫자를 D' 'D {4}'리터럴 문자가 일치하는 패턴을 @Eric – Eric

+0

/connect=;;(.+?);;d{4};;/' . – rpaskett

+0

@rpaskett true, true – Eric

답변

4

그냥 위의 대답에 약간의 확장 지 IP 검출에 대해 좀 더 똑똑하지만, 샘플이 잘 형성 되었다면, 이것으로 충분할 것입니다.

http://3v4l.org/FpGFD

5

이 방법을 시도 ...

$re = "/connect=;;(.+?);;(\d{4});;/"; 
    $str = "/connect=;;41.26.162.36;;192.168.0.100;;8081;;/connect=;;98.250.16.76;; 
    192.168.0.24;;8080;;/connect=;;216.152.60.12;;192.168.1.103;;8090;;/connect=;; 
    91.11.65.110;;192.168.1.3;;8081;;"; 

    preg_match_all($re, $str, $matches); 

설명 :

if (preg_match_all('/connect=;;([\d\.]+);;([\d\.]+);;(\d+);;/', 
        $long, $matches, PREG_SET_ORDER)) { 
    foreach($matches as $match) { 
    list(,$ip1, $ip2, $port) = $match; 
    /* Do stuff */ 
    echo "{$ip1} => {$ip2}:{$port}\n"; 
    } 
} 

당신은 할 수 :

/connect=;;(.+?);;(\d{4});;/g 

    connect=;; matches the characters connect=;; literally (case sensitive) 
    1st Capturing group (.+?) 
    .+? matches any character (except newline) 
     Quantifier: +? Between one and unlimited times, as few times as possible, 
    expanding as needed [lazy] 
    ;; matches the characters ;; literally 
    2nd Capturing group (\d{4}) 
    \d{4} match a digit [0-9] 
     Quantifier: {4} Exactly 4 times 
    ;; matches the characters ;; literally 
    g modifier: global. All matches (don't return on first match) 

enter image description here

+0

이 코드는 두 번째 (로컬 IP 주소)를 피하는 방법은 무엇입니까? /connect=;;(.+ ?) ;; (\ d {4}) ;;/";'결과 :'41.26.162.36 ;; 192.168.0.100' – user1294097

관련 문제