php 用于检测 base64 编码字符串的 RegEx

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8106038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:58:53  来源:igfitidea点击:

RegEx for detecting base64 encoded strings

phpregexbase64

提问by federico-t

I need to detect strings with the form @base64(e.g. @VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==) in my application.

我需要在我的应用程序中检测@base64(例如@VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==)形式的字符串。

The @ has to be at the beginning and the charset for base64 encoded strings is a-z, A-Z, 0-9, +, /and =. Would be the appropiate regular expresion to detect them?

@ 必须在开头,base64 编码字符串的字符集是a-z, A-Z, 0-9, +,/=。将是适当的正则表达式来检测它们吗?

Thanks

谢谢

回答by Regexident

Something like this should do (does not check for proper length!):

这样的事情应该做(不检查正确的长度!):

^@[a-zA-Z0-9+/]+={,2}$


The length of any base64 encoded string must be a multiple of 4, hence the additional.

任何 base64 编码字符串的长度必须是 4 的倍数,因此是额外的。

See here for a solution that checks against proper length: RegEx to parse or validate Base64 data

请参阅此处以获取检查正确长度的解决方案:RegEx to parse or validate Base64 data

A quick explanation of the regex from the linked answer:

链接答案中正则表达式的快速解释:

^@ #match "@" at beginning of string
(?:[A-Za-z0-9+/]{4})* #match any number of 4-letter blocks of the base64 char set
(?:
    [A-Za-z0-9+/]{2}== #match 2-letter block of the base64 char set followed by "==", together forming a 4-letter block
| # or
    [A-Za-z0-9+/]{3}= #match 3-letter block of the base64 char set followed by "=", together forming a 4-letter block
)?
$ #match end of string

回答by Federico Quagliotto

try with:

尝试:

^@(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$

=> RegEx to parse or validate Base64 data

=> RegEx 解析或验证 Base64 数据