0

I got a text file (testfile.txt) containing

127.0.0.1:80
127.0.0.1:90
127.0.0.1:100 127.0.0.1:230
127.0.0.1:110
127.0.0.1:200
127.0.0.1:201 127.0.0.1:45
127.0.0.1:86
(...)

In order to fix lines such as 127.0.0.1:100 127.0.0.1:230 and 127.0.0.1:201127.0.0.1:45 I'm using this script (POST METHOD):

$listValue = "";

    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        if(!empty($_POST['list']))
        $res = preg_match_all("/\d+\.\d+\.\d+\.\d+\:\d+/", $_POST['list'], $match);

        if($res)
        foreach($match[0] as $value)
        $listValue .= $value."\n";

and on Submit:

echo trim($listValue);

Script returns:

127.0.0.1:80
127.0.0.1:90
127.0.0.1:100
127.0.0.1:230
127.0.0.1:110
127.0.0.1:200
127.0.0.1:201
127.0.0.1:86
(...)

I need this script to read from testfile.txt and to save to testfile.txt. Any ideas? Cheers

4

1 回答 1

1

This should do what you want:

$list = file_get_contents('testfile.txt');
$res = preg_match_all("/\d+\.\d+\.\d+\.\d+\:\d+/", $list, $match);

if($res) {
    foreach($match[0] as $value)
        $listValue .= $value."\n";
    file_put_contents('testfile.txt', trim($listValue));
}

Edit: Also, instead of the regexp, you could do a simple str_replace(' ', "\n", $list)

于 2013-08-08T11:46:20.120 回答