Reputation: 906
I am trying to parse some data from external site to local script. Local script cals remote page with some get data to initiate response. Returning the required data in the headers of the remote script, in this case data is "key" string.
Now the remote page also outputs a load of other headers, the one we are after is called LicenceID unfourtunalty the array crerated by get_headers seems to include the header title in the value, not the key. So am trying some regex to match the header value, which would look somthing like this:
licenceID: dfkfdlsdlghgsldghsld
function check_path($path)
{
$headers = @get_headers($path);
var_dump($headers);
//while (list($key, $value) = each($headers))
foreach($headers as $key => $value)
{
echo "$key - $value<br />";
//if(preg_match('/^.*licenceID:*$/',$value))
if (preg_match('/^.*licenceID.*$/i', $dictionary, $matches))
{
echo "found";
echo "$key - $value<br />";
$position = strpos($value, ':');
$clean_value = substr($value, $position);
$clean_up = trim_string($clean_value,":");
return $clean_up;
}
else
{
return false;
}
}
}
Having trouble with the regex in the line if (preg_match('/^.licenceID.$/i', $dictionary, $matches))
cant seem to get it to match, also needs to strip out the licenceID: from the value and only return the data after the :
Suggestions welcome!
Upvotes: 1
Views: 218
Reputation: 906
so final function looks like this:
function check_path($path)
{
$headers = @get_headers($path);
$licenseID = preg_grep('~licenceID~i', $headers);
$licenseID = preg_replace('~licenceID:\s+~i', '', $licenseID); // clean-up
if($licenseID)
{
return $licenseID['7'];
}
else
{
return false;
}
}
thanks to Alix Axel for the preg_grep suggestion and spotting the mistake in the return false else statement. of course it was always returning false! doh.
Upvotes: 0
Reputation: 154613
I think you're having trouble because you are returning false inside the foreach loop, unless licenceID
is the first header it will always return false. Here are some simplified solutions:
Using preg_grep()
$headers = @get_headers($path);
$licenseID = preg_grep('~licenceID~i', $headers);
$licenseID = preg_replace('~licenceID:\s+~i', '', $licenseID); // clean-up
Or, like @Glass Robot suggested:
$headers = @get_headers($path, 1);
$licenseID = $headers['licenceID'];
I haven't tested this, but it should work.
Upvotes: 1
Reputation: 2448
You could just use substr():
function check_path($path)
{
$headers = @get_headers($path);
var_dump($headers);
foreach($headers as $key => $value)
{
echo "$key - $value<br />";
if ('licenceID:' == substr($value, 0, 10))
{
echo "found";
echo "$key - $value<br />";
$clean_value = substr($value, 10);
$clean_up = trim($clean_value);
return $clean_up;
}
else
{
return false;
}
}
}
Upvotes: 1