正则表达式和制表符分隔的数据文件

时间:2014-02-24 15:39:32

标签: php regex database

我想构建一个制表符分隔的数据文件。我使用正则表达式来提取所需信息,即注册人姓名,注册人电子邮件和域名。我希望以制表符分隔格式的每个域查找的代码输出结果。能否请你告诉我如何实现这一目标?

<?php

     require 'Net/Whois.php';
     $server = 'whois.networksolutions.com';


    $content=file('query-file.txt');

    foreach ($content as $query)

    { 


    $whois = new Net_Whois;
    $data = $whois->query($query, $server);

               if (preg_match_all('/^registrant name: (.*)/im', $data, $matches, PREG_SET_ORDER))

                    // Print the matches:
                    {
                            echo '<pre>' .  $matches[0][1] .  '</pre>';

                     } else {

                     echo 'not found!</p>';
                     }  


      if (preg_match_all('/^registrant email: (.*)/im', $data, $email, PREG_SET_ORDER))

                    // Print the matches:
                    {
                            echo '<pre>' .  $email[0][1] .  '</pre>';

                     } else {

                     echo 'not found!</p>';
                     }      

        if (preg_match_all('/^Domain Name: (.*)/im', $data, $email, PREG_SET_ORDER))

                    // Print the matches:
                    {
                            echo '<pre>' .  $email[0][1] .  '</pre>';

                     } else {

                     echo 'not found!</p>';
                     }                    


    }

?> 

输出代码

Dns Admin

dns-admin@google.com

google.com

not found!

not found!

not found!

Domain Name Manager

tmgroup@turner.com

cnn.com

Domain Administrator

domains@microsoft.com

msn.com

Domain Administrator

domains@microsoft.com

hotmail.com

Domain Administrator

domainadmin@yahoo-inc.com

yahoo.com

DNS Admin

gmail-abuse@google.com

gmail.com

希望的输出应该看起来像

Dns Admin   dns-admin@google.com   google.com
Domain Name Manager   tmgroup@turner.com    cnn.com
Domain Administrator   domains@microsoft.com   msn.com

...

1 个答案:

答案 0 :(得分:0)

而不是echo将数据保存到每个if语句的数组中:

$data[] = $matches[0][1];

否则

$data[] = 'not found!';

然后在循环结束时(在最后一个if之后),使用制表符加入数据:

$lines[] = implode("\t", $data) . "\n";

然后在循环结束后(})将行保存到文件中:

file_put_contents('path/to/file.txt', $lines);