PHP函数存储数组中的元素

时间:2015-05-15 14:30:44

标签: php arrays

我正在使用前端Javascript文本编辑器,以html格式提交数据,还将所有图像转换为base64编码格式。

以下函数将解析$ _POST super global,用于html内容并将编码图像存储在images文件夹中,并附带相应的扩展名。

$html = preg_replace_callback("/src=\"data:([^\"]+)\"/", function ($matches) {
    list($contentType, $encContent) = explode(';', $matches[1]);
    if (substr($encContent, 0, 6) != 'base64') {
        return $matches[0];
    }
    $imgBase64 = substr($encContent, 6);
    $imgFilename = md5($imgBase64); // Get unique filename
    $imgExt = '';
    switch($contentType) {
        case 'image/jpeg':  $imgExt = 'jpg'; break;
        case 'image/gif':   $imgExt = 'gif'; break;
        case 'image/png':   $imgExt = 'png'; break;
        default:            return $matches[0]; 
    }

   // Here is where I'm able to echo image names with thier extentions.
   echo $imgFilename . '.' . $imgExt;

    $imgPath = 'zendesk-images/'.$imgFilename.'.'.$imgExt;
    // Save the file to disk if it doesn't exist
    if (!file_exists($imgPath)) {
        $imgDecoded = base64_decode($imgBase64);
        $fp = fopen($imgPath, 'w');
        if (!$fp) {
            return $matches[0];
        }
        fwrite($fp, $imgDecoded);
        fclose($fp);
    }
    return 'src="'.$imgPath.'"';
}, $html);

我能够在以下行中回显图像名称

echo $imgFilename . '.' . $imgExt;

我正在尝试将转换后的图像文件名存储在一个数组中,但我没有成功地这样做。

这是我试过的,在函数

之前初始化一个数组
$Images = array(); 
然后,我试图做以下事情,而不是回应。

$Images[] = $imgFilename . '.' . $imgExt; 

但那不起作用,我最终得到空数组

1 个答案:

答案 0 :(得分:0)

如果你想在外部范围内使用$ images,你需要像

这样的东西
$images = array();
$html = preg_replace_callback("/src=\"data:([^\"]+)\"/", function ($matches) use(&$images) {
    //...
    $images[] = $imgFilename . '.' . $imgExt;
    //...
}
echo implode(', ', $images);
相关问题