PHP如何preg匹配此字符串?

use*_*097 3 php regex preg-match

我有很长的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;;
Run Code Online (Sandbox Code Playgroud)

我使用以下方法预先匹配全局IP地址没有问题:

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

这对我来说非常有效,但我无法弄清楚如何预先匹配位于该行尾的端口.

Sar*_*ara 6

只是为了扩展上述答案:

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";
  }
}
Run Code Online (Sandbox Code Playgroud)

您可能会在IP检测方面变得更加聪明,但是如果您的样本格式正确,那么这就足够了。

http://3v4l.org/FpGFD


Alw*_*nny 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);
Run Code Online (Sandbox Code Playgroud)

说明:

  /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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述