例如,这是一个纯文本段落: -
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
如何使用PHP提取特定单词?
说我需要注册商,名称服务器和状态。我需要它在不同的变量。名称服务器变量可以在数组中,因为它不止一个。
答案 0 :(得分:4)
这是一个应该按要求执行的代码段:
$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);
它的作用是:
输出结果为:
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
)
答案 1 :(得分:0)
您可以使用正则表达式匹配来获取所需的值 e.g。
preg_match('^(?P<key>[a-zA-Z\s]):\s(?P<val>.*)$', $text, $matches);
var_dump($matches);
更新: - 请使用以下代码 -
preg_match_all('/(?P<key>[a-zA-Z\s]+):\s(?P<val>.*)\n/', $text, $matches);
var_dump($matches);
关于正则表达式,这些称为命名子组。请参阅http://php.net/manual/en/function.preg-match.php
上的示例#4