不确定您是否可以仅使用正则表达式来处理它,如果是 utf-8 文件名,您还应该对文件名进行 urldecode。此外,它可以出现在name 或filename 属性下。这是我的解决方案:
function getFilenameFromDisposition($value)
{
$value = trim($value);
if (strpos($value, ';') === false) {
return null;
}
list($type, $attr_parts) = explode(';', $value, 2);
$attr_parts = explode(';', $attr_parts);
$attributes = array();
foreach ($attr_parts as $part) {
if (strpos($part, '=') === false) {
continue;
}
list($key, $value) = explode('=', $part, 2);
$attributes[trim($key)] = trim($value);
}
$attrNames = ['filename*' => true, 'filename' => false];
$filename = null;
$isUtf8 = false;
foreach ($attrNames as $attrName => $utf8) {
if (!empty($attributes[$attrName])) {
$filename = trim($attributes[$attrName]);
$isUtf8 = $utf8;
break;
}
}
if ($filename === null) {
return null;
}
if ($isUtf8 && strpos($filename, "utf-8''") === 0 && $filename = substr($filename, strlen("utf-8''"))) {
return rawurldecode($filename);
}
if (substr($filename, 0, 1) === '"' && substr($filename, -1, 1) === '"') {
$filename = substr($filename, 1, -1);
}
return $filename;
}
测试:
attachment; filename*=utf-8''%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82.doc -> привет.doc
attachment; filename="hello.pdf" -> hello.pdf
attachment; filename=hello.png -> hello.png
inline; name=field1 -> null
attachment; -> null
attachment; filename= -> null