Home > Backend Development > PHP Tutorial > preg_match_all - php正则表达式问题

preg_match_all - php正则表达式问题

WBOY
Release: 2016-06-06 20:33:42
Original
1015 people have browsed it

如何匹配

<code>$rs='callback( {"client_id":"101223150","openid":"9ECFD84190F7D5D40E013CF84D0979FF"} );';
</code>
Copy after login
Copy after login

中openid的9ECFD84190F7D5D40E013CF84D0979FF?

回复内容:

如何匹配

<code>$rs='callback( {"client_id":"101223150","openid":"9ECFD84190F7D5D40E013CF84D0979FF"} );';
</code>
Copy after login
Copy after login

中openid的9ECFD84190F7D5D40E013CF84D0979FF?

可以使用正则前瞻

举个例子,需要匹配 <p>Hello world</p> 中的 Hello world,正则表达式可以这么写:(?)(.*)(?=

)

所以获取 openid 的值可以这样:

<code class="php"><?php $rs='callback( {"client_id":"101223150","openid":"9ECFD84190F7D5D40E013CF84D0979FF"} );';
$pattern = '/(?<=openid":")(.*)(?=")/';
preg_match($pattern, $rs, $matches);
print_r($matches);</code></code>
Copy after login

输出:

<code class="console">Array
(
    [0] => 9ECFD84190F7D5D40E013CF84D0979FF
    [1] => 9ECFD84190F7D5D40E013CF84D0979FF
)</code>
Copy after login

<code>php</code><code>preg_match_all('@callback\((.*)\);@', $rs,$matches );
$arr = json_decode($matches[1][0],true);
print_r($arr['openid']);//9ECFD84190F7D5D40E013CF84D0979FF
</code>
Copy after login

这是一个标准的jsonp格式(json参数+回调函数),一个简单的处理方案是拿出函数callback()取它的参数部分然后作为json解析:

<code>php</code><code>$rs = 'callback( {"client_id":"101223150","openid":"9ECFD84190F7D5D40E013CF84D0979FF"} );';
$jsonp = [];
preg_match('/callback\((.+)\);/', $rs, $jsonp);
print_r($jsonp);
$result = json_decode($jsonp[1]);
print_r($result); //使用$result->openid访问你需要的数据
</code>
Copy after login

输出

<code>Array
(
    [0] => callback( {"client_id":"101223150","openid":"9ECFD84190F7D5D40E013CF84D0979FF"} );
    [1] =>  {"client_id":"101223150","openid":"9ECFD84190F7D5D40E013CF84D0979FF"}
)
stdClass Object
(
    [client_id] => 101223150
    [openid] => 9ECFD84190F7D5D40E013CF84D0979FF
)
</code>
Copy after login

代码如下:

<code>php</code><code>$rs='callback( {"client_id":"101223150","openid":"9ECFD84190F7D5D40E013CF84D0979FF"} );';
$preg = '/openid["|\']:["|\'](\w+)/i';
preg_match($preg,$rs,$result);
echo $result[1];//9ECFD84190F7D5D40E013CF84D0979FF
</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template