开发者

How do I extract particular words from a paragraph using PHP?

开发者 https://www.devze.com 2023-01-08 02:24 出处:网络
hi for example this is a plain text paragraph:- Domain Name: COMCAST.NET Registrar: CSC CORPORATE DOMAINS, INC.

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.


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
)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消