PHP在特定字符串之间读取

时间:2017-09-19 12:41:45

标签: php

我正在将传出流量记录在一个文本文件中,该文件由ip&港口。 将所有日志复制到文本文件并进一步将其内容复制到php字符串后,我需要显示所有ips。

代码:

<?php
function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

$fullstring = "[IP]49.44.50.18[/IP][PORT]80[/PORT] [IP]204.79.197.200[/IP][PORT]80[/PORT] [IP]49.44.50.18[/IP][PORT]80[/PORT] [IP]204.79.197.203[/IP][PORT]80[/PORT] [IP]204.79.197.200[/IP][PORT]80[/PORT] [IP]49.44.50.18[/IP][PORT]80[/PORT] [IP]204.79.197.203[/IP][PORT]80[/PORT] [IP]204.79.197.200[/IP][PORT]80[/PORT] [IP]49.44.50.18[/IP][PORT]80[/PORT] [IP]111.221.29.30[/IP][PORT]80[/PORT] [IP]23.99.125.55[/IP][PORT]80[/PORT] [IP]103.243.221.87[/IP][PORT]80[/PORT] [IP]107.21.211.226[/IP][PORT]80[/PORT] [IP]49.44.118.224[/IP][PORT]443[/PORT] [IP]49.44.50.9[/IP][PORT]80[/PORT] [IP]204.79.197.200[/IP][PORT]80[/PORT] [IP]46.137.205.158[/IP][PORT]80[/PORT] [IP]46.137.205.249[/IP][PORT]443[/PORT] [IP]204.79.197.200[/IP][PORT]80[/PORT] [IP]13.107.5.80[/IP][PORT]80[/PORT] [IP]103.243.221.87[/IP][PORT]443[/PORT] [IP]204.79.197.203[/IP][PORT]80[/PORT] [IP]204.79.197.200[/IP][PORT]80[/PORT] [IP]49.44.50.18[/IP][PORT]80[/PORT] [IP]175.41.140.23[/IP][PORT]443[/PORT] [IP]144.2.1.1[/IP][PORT]443[/PORT] [IP]111.221.29.30[/IP][PORT]80[/PORT] [IP]23.99.125.55[/IP][PORT]80[/PORT] [IP]103.243.221.87[/IP][PORT]80[/PORT] [IP]107.21.211.226[/IP][PORT]80[/PORT] [IP]49.44.118.224[/IP][PORT]443[/PORT] [IP]49.44.50.9[/IP][PORT]80[/PORT] [IP]204.79.197.200[/IP][PORT]80[/PORT] [IP]46.137.205.158[/IP][PORT]80[/PORT] [IP]46.137.205.249[/IP][PORT]443[/PORT] [IP]204.79.197.200[/IP][PORT]80[/PORT] [IP]13.107.5.80[/IP][PORT]80[/PORT] [IP]103.243.221.87[/IP][PORT]443[/PORT] [IP]204.79.197.203[/IP][PORT]80[/PORT] [IP]204.79.197.200[/IP][PORT]80[/PORT] [IP]49.44.50.18[/IP][PORT]80[/PORT] [IP]175.41.140.23[/IP][PORT]443[/PORT] [IP]144.2.1.1[/IP][PORT]443[/PORT] [IP]111.221.29.30[/IP][PORT]80[/PORT] [IP]23.99.125.55[/IP][PORT]80[/PORT] [IP]103.243.221.87[/IP][PORT]80[/PORT] [IP]107.21.211.226[/IP][PORT]80[/PORT]";
$parsed = get_string_between($fullstring, '[IP]', '[/IP]');

echo $parsed;
?>

输出:

49.44.50.18

如何显示所有IP

2 个答案:

答案 0 :(得分:1)

尝试:

preg_match_all('#\[IP\]([^\[]+)\[/IP\]#', $fullstring, $ips);
var_dump($ips[1]);

答案 1 :(得分:0)

The below code may help you
<?php
function get_all_ips($string){

    $AllIP = explode(' ',$string);

    $FilteredIPs = array();

    foreach($AllIP as $IP){

        preg_match('/[0-9\.]+/',$string,$output);

        if(filter_var($output[0],FILTER_VALIDATE_IP)){

            $FilteredIPs[] = $output[0];
        }
    }

    return $FilteredIPs;   
}
$parsed = get_all_ips($fullstring);
var_dump($parsed);
?>