正则表达式匹配URL中的JSON Web令牌

时间:2016-03-01 10:05:18

标签: php regex jwt

我需要一点帮助来改进这个正则表达式,以便能够使用PHP在URL字符串中识别JWT令牌。这匹配令牌很好,但如果我附加另一个URI段则不会。

到目前为止的正则表达式:

/[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)$/

这适用于以下网址:

http://not.website.com/**eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ**

它不起作用的网址(请注意最后的其他细分)

http://not.website.com/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ/additional/segments

预期匹配应如下所示:

http://not.website.com/**eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ**/additional/segments

3 个答案:

答案 0 :(得分:4)

根据这些网址字符串的出现位置(文字或独立),您可以simply do

PHP

$string = 'http://not.website.com/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ/additional/segments'; $regex = '~ # delimiter ^https?://.+?/ # match http:// or https:// + anything up to a / lazily (?P<token>[^/\n\r]+) # capture everything that is not a / or newline (for this demo) to the group "token" ~x'; # delimiter preg_match($regex, $string, $match); echo $match["token"]; # access your token in the $match array // output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ 中,这将是:

{{1}}

请参阅a demo on ideone.com

答案 1 :(得分:1)

你可以用这种方式修改你的正则表达式

  

[A-ZA-Z0-9 -_] +?[A-ZA-Z0-9 -_] +?([A-ZA-Z0-9 -_] +)[/ A-ZA -Z0-9 -_] +?$

添加

$ 之前

[/ a-zA-Z0-9 -_] *?

(可选:(*?)所以额外的正斜杠和字符将覆盖在上面的模式中)

答案 2 :(得分:0)

/(http:\/\/[a-zA-Z0-9\-_\.]+)(\/[a-zA-Z0-9\-_\.]+)(\/[a-zA-Z0-9\-_]*)*$/

您的令牌将从第二组中提取 见https://regex101.com/r/fO9dR4/1