2009-06-24 80 views
1

存储值我有一个字符串,它看起来是这样的:找到并从字符串

$fetched = name=myName zip=420424 country=myCountry; 
// and so on, it is not an array 

我从API获取这些值。

我只想要zip = 873289(事实上只有数字)。

于是我就用:

// $fetched above is the output of the function below 
$fetched = file_get_contents("http://example.com"); 

这样,我取的内容,可以使用此代码

​​

匹配,但我想它存储在变量,什么是功能存储匹配结果?

回答

2

您需要指明要使用括号来捕捉部分,然后提供一个额外的参数的preg_match到它们挑出来:

$matches=array(); 
if (preg_match ('/zip=([0-9]+)/', $fetched, $matches)) 
{ 
    $zip=$matches[1]; 
} 
0

preg_match()存储其结果在第三个参数,这是通过by reference。因此,而不是:

$zip = preg_match ('/zip=[0-9]+/', $fetched); 

你应该有:

preg_match ('/zip=[0-9]+/', $fetched, $zip);