tags:

views:

38

answers:

2

Hello,

i have a string which looks something like this:

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

I fetch these values from an api.

I want only the zip=873289 (infact only the numbers).

So i use:

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

this way i fetch the contents and can match it with this code

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

but i want to store it in the variable, what is function to store the matched results?

Thank You.

+3  A: 

You need to indicate the part you want to capture with parentheses, then supply an extra parameter to preg_match to pick these up:

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

preg_match() stores its result in the third argument, which is passed by reference. So instead of:

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

You should have:

preg_match ('/zip=[0-9]+/', $fetched, $zip);
Ionuț G. Stan