问题描述
<?php
$a="https://sayat.me/chitmarike";
$html=file_get_contents("$a");
$headers = get_headers($a);
preg_match('~id="bar" value="([^"]*)"~', $html, $img);
$img1 = $img[1];
echo $img1;
preg_match('/(?<=csam=).*?(?=;)/', $headers, $cook);
$cook1 = $cook[1];
echo $cook1;
?>
我想从cookie标头中提取csam
的值.
看起来像这样:
I want to extract the value of csam
from the cookie header.
This is what it looks like:
Array
(
[0] => HTTP/1.1 200 OK
[1] => Date: Fri, 07 Apr 2017 19:05:03 GMT
[2] => Content-Type: text/html; charset=UTF-8
[3] => Connection: close
[4] => Set-Cookie: __cfduid=d6dea25f00686a7cef5f0a3d21195207c1491599902; expires=Sat, 07-Apr-18 19:05:23 GMT; path=/; domain=.sayat.me; HttpOnly
[5] => Set-Cookie: PHPSESSID=m3hvgquu2vtcp9ingqmkttqgs2; path=/
[6] => Expires: Thu, 19 Nov 1981 08:52:00 GMT
[7] => Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
[8] => Pragma: no-cache
[9] => Set-Cookie: csam=5844bc1d44; expires=Fri, 07-Apr-2017 19:35:36 GMT; Max-Age=1800; path=/
[10] => X-CSRF-Protection: SAM v2.0
[11] => Set-Cookie: country=IN; expires=Sun, 07-May-2017 19:05:36 GMT; Max-Age=2592000; path=/
[12] => Vary: Accept-Encoding
[13] => McID: sam-web4
[14] => Server: cloudflare-nginx
[15] => CF-RAY: 34bf420dae9069fb-LHR
)
但是我遇到了这个错误
我在做什么错了?
推荐答案
花费时间阅读和很好地理解错误消息并不是浪费时间.错误消息简单明了:preg_match() expects parameter 2 to be string, array given
.结论,在preg_match('/(?<=csam=).*?(?=;)/', $headers, $cook);
中,当 preg_match
期望主题(第二个参数)是一个字符串,仅此而已.
Spending time to read and well understand an error message isn't wasted time. Error messages are simple and clear: preg_match() expects parameter 2 to be string, array given
. Conclusion, in: preg_match('/(?<=csam=).*?(?=;)/', $headers, $cook);
, $headers
is an array when preg_match
expects the subject (the second parameter) to be a string, nothing more, nothing less.
问题,$headers
由 get_headers
填充返回一个数组.解决此问题的两种可能方法:
Problem, $headers
is filled by get_headers
that returns an array. Two possible ways to solve the problem:
- 插入数组并使用您的模式搜索结果字符串,或像这样重写它:
/csam=\K[^;]+/
- 将
get_headers
的第二个参数设置为1,并使用数组结构查找所需的信息:
- implode the array and search the resulting string with your pattern or rewrite it like this:
/csam=\K[^;]+/
- set the second parameter of
get_headers
to 1 and use the array structure to find the information you want:
示例:
$a="https://sayat.me/chitmarike";
$headers = get_headers($a, 1);
foreach ($headers['Set-Cookie'] as $v) {
if ( strpos($v, 'csam=') === 0 ) {
$cook = substr($v, 5, strpos($v, ';') - 5);
break;
}
}
这篇关于preg_match()期望参数2为字符串,数组给定不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!