确定一个值是base64字符串还是图像URL的最佳方法是什么


What is the best method to determine if a value is either a base64 string or an image URL?

我有一个值,它可能是图像URL或图像Base64字符串。确定哪个是哪个的最佳方法是什么?如果它是一个图像URL,那么该图像将已经驻留在我的服务器上。

我试过做一个preg_match,但我认为在一个潜在的巨大base64字符串上运行一个pret_match将是服务器密集型的。

编辑:迄今为止最好的两种方法。

// if not base64 URL
if (substr($str, 0, 5) !== 'data:') {}
// if file exists
if (file_exists($str)) {}

您的意思是要区分

<img src="http://example.com/kittens.jpg" />
and
<img src="data:image/png;base64,...." />

您只需要查看src属性的前5个字符,就可以判断它是否是一个数据uri,例如

if (substr($src, 0, 5) == 'data:')) {
    ... got a data uri ...
}

如果它看起来不像一个数据uri,那么可以放心地假设它是一个URL并将其视为URL。

如果只有两种可能性,您可以执行以下操作:

$string = 'xxx';
$part = substr($string, 0, 6); //if an image, it will extract upto http(s):
if(strstr($part, ':')) {
    //image
} else {
    //not an image
}

解释:上面的代码假设输入是base64字符串或图像。如果是图像,它将并且应该包含协议信息(包括:)。这在base64编码的字符串中是不允许的。

您可以使用preg_match()执行此操作。当preg_match没有看到d时,代码将停止。如果它发现一个d后面没有a,它就会停止,以此类推。同样,这样你就不会做多余的数学和字符串解析:

if(!preg_match('!^data':!',$str) {
  //image
} else {
  //stream
}

您也可以使用is_file(),它不会在目录中返回true。

// if file exists and is a file and not a directory
if (is_file($str)) {}