All welcome.

It is necessary to extract all ip addresses from the string using regexp and write to the file. But, the array obtained with regexp takes an awkward look, how can you alter this code so that all ip addresses are recorded?

$string = "127.0.0.1:8000 127.0.0.1:81 127.0.0.1:77 127.0.0.1:66"; preg_match_all("/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,5})/", $string, $result); $res = ''; foreach($result as $key => $value) { $res .= $value[$key]."\r\n"; } file_put_contents('text.txt', $res); 

(Only the first 2 IP addresses are recorded)

var_dump:

 array(2) { [0]=> array(4) { [0]=> string(14) "127.0.0.1:8000" [1]=> string(12) "127.0.0.1:81" [2]=> string(12) "127.0.0.1:77" [3]=> string(12) "127.0.0.1:66" } [1]=> array(4) { [0]=> string(14) "127.0.0.1:8000" [1]=> string(12) "127.0.0.1:81" [2]=> string(12) "127.0.0.1:77" [3]=> string(12) "127.0.0.1:66" } } 

Thank you in advance.

    1 answer 1

    1. No need to use regular expressions anywhere, your task is perfectly solved through explode . Code on ideone.com ;
    2. The contents of the $res variable are written to a file, but if you go up the code a little higher, it is reset to zero and is not filled with anything.
    • @ ua6xh, thank you. But I would be interested in how to convert this array and write the contents? + There may be such a situation: TEXT127.0.0.1: 80TEXT, explode will not help ... - evansive
    • one
      @evansive 1. You have presented the situation not TEXT127.0.0.1:80TEXT , but \sIP\s , we are not psychics here. 2. Make print_r($result); after preg_match_all and see what you have there. There is an array of 2 elements, the 1st is where the string was found, the 2nd is what got into the search group in a regular expression. You need to view the second array in a loop. foreach($result[1] as $key => $value) {...someCode...} - Opalosolo
    • @ ua6xh, thanks for explaining how the data is distributed in this array, now I understand everything. - evansive