validating a base64 encoded string using regular expression

We can validate a base64 encoded string using a nice regex (regular expression). The following regex can be used with any programming language. I would use php for the example. The regex is as follows.

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

Which will also detect the usage of = or == at the end of the string (and only end).

A function geared specifically toward this:

<?phpfunction is_base64_encoded()
 {
     if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $data)) {
           return TRUE;
      } 
     else {
             return FALSE;
       }
 };
 is_base64_encoded("iash21iawhdj98UH3"); // true
 is_base64_encoded("#iu3498r"); // false
 is_base64_encoded("asiudfh9w=8uihf"); // false
 is_base64_encoded("a398UIhnj43f/1!+sadfh3w84hduihhjw=="); // false
?>
 
Dost Muhammad Shah

Dost Muhammad Shah

Dost Muhammad specializing in Embedded Design, Firmware development, PCB designing , testing and prototyping. He enjoys sharing his experience with others .Get in touch with Dost on Twitter or via Contact form

 

2 thoughts on “validating a base64 encoded string using regular expression

  1. Can you explain this regex match for the last one?
    I haven’t used the php variant of re but I’ve used them extensively on bash and python.

    According to my understating (and it does fail in bash) the last test case should fail.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.