Base64 & JSON Encode array in PHP, use as HTML data attribute, decode and parse in JavaScript …. with proper Escaping

The possible output of base64_encode() contains a-zA-Z0-9+/ and possibly = or == appended.

Testing with

$str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=";

we find that:

esc_attr( $str ) === $str 

is true, so it looks like esc_attr() preserves base64 encoded strings.

There are possible regexes to help with validation, but according to this answer by @BoltClock, we could check it with the second strict parameter of:

base64_decode( $str, $strict = true )

We could then wrap it in a function like:

function is_base64( $str )
{
    return base64_decode( $str, true) !== false;
}

to validate it in PHP.