tags:

views:

48

answers:

2

hi for example this is a plain text paragraph:-

Domain Name: COMCAST.NET
Registrar: CSC CORPORATE DOMAINS, INC.
Whois Server: whois.corporatedomains.com
Referral URL: http://www.cscglobal.com
Name Server: DNS101.COMCAST.NET
Name Server: DNS102.COMCAST.NET
Name Server: DNS103.COMCAST.NET
Name Server: DNS104.COMCAST.NET
Name Server: DNS105.COMCAST.NET
Status: clientTransferProhibited
Updated Date: 21-jan-2010
Creation Date: 25-sep-1997
Expiration Date: 24-sep-2012

How do I extract particular words using PHP??

say I need Registrar,Name Servers and status. I need it in different variables. Name server variables can be in array as it is more than one. any hope??

A: 

You can use regular expression matching to get the desired values e.g.

preg_match('^(?P<key>[a-zA-Z\s]):\s(?P<val>.*)$', $text, $matches);
var_dump($matches);

UPDATE: -- Please use the below code --

preg_match_all('/(?P<key>[a-zA-Z\s]+):\s(?P<val>.*)\n/', $text, $matches);
var_dump($matches);

Regarding the regular expressions, these are called named subgroups. Please refer example #4 on http://php.net/manual/en/function.preg-match.php

Gunjan
Getting some error No ending delimiter '^' found. and the place of <key> do I need to change anything?? and what about <val>?? this kind of expression is very new to me...
mathew
ok.. sorry I didn't check before posting... there were a couple of mistakes. Please refer to updates above
Gunjan
+4  A: 

Here's a snippet that should do as requested:

$lines = explode("\n", $data);

$output = array();
foreach($lines as $line)
{
    list($key, $value) = explode(': ', $line, 2);
    if(isset($output[$key]))
    {
        if(!is_array($output[$key]))
        {
            $tmp_val = $output[$key];
            $output[$key] = array($tmp_val);
        }
        $output[$key][] = $value;
    }
    else
    {
        $output[$key] = $value;
    }
}
print_r($output);

What it does is:

  • It splits the data in lines
  • Gets the key/value pairs
  • Than it appends it to the output array, creating an extra nesting level on duplicate keys

The output is:

Array
(
    [Domain Name] => COMCAST.NET
    [Registrar] => CSC CORPORATE DOMAINS, INC.
    [Whois Server] => whois.corporatedomains.com
    [Referral URL] => http://www.cscglobal.com
    [Name Server] => Array
        (
            [0] => DNS101.COMCAST.NET
            [1] => DNS102.COMCAST.NET
            [2] => DNS103.COMCAST.NET
            [3] => DNS104.COMCAST.NET
            [4] => DNS105.COMCAST.NET
        )

    [Status] => clientTransferProhibited
    [Updated Date] => 21-jan-2010
    [Creation Date] => 25-sep-1997
    [Expiration Date] => 24-sep-2012
)
Dennis Haarbrink
Great Dennis. Thanks man.
mathew
You're welcome!
Dennis Haarbrink