nhance/app/Helpers/ExcelSanitizeHelper.php

47 lines
1.8 KiB
PHP

<?php
namespace App\Helpers;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
class ExcelSanitizeHelper
{
/**
* Regex pattern for non-printable characters to be removed from strings.
*
* This pattern includes control characters, zero-width characters, and Excel-specific codes
*/
private static $nonPrintablePattern = '/[\x00-\x1F\x7F\x{200B}\x{200C}]|_x[0-9A-F]{4}_/u';
/**
* Sanitizes array data by removing non-printable characters and trimming whitespace from strings.
*
* @param array $data Input array containing data to sanitize
* @return array Sanitized array with non-printable characters removed and leading/trailing whitespace trimmed
*/
public static function sanitizeArrayData(array $data): array
{
try {
$cleanData = [];
foreach ($data as $key => $value) {
if (is_array($value)) {
$cleanData[$key] = self::sanitizeArrayData($value); // Recursive call for nested arrays
} elseif (is_string($value)) {
// Remove non-printable characters and trim whitespace from strings
$value = str_replace("\u00a0", " ", $value);
$cleanData[$key] = trim(preg_replace(self::$nonPrintablePattern, '', $value));
} else {
$cleanData[$key] = $value; // Keep non-string/non-array data as is
}
}
return $cleanData;
} catch (\Exception $e) {
// Log the error and the problematic data for debugging
log_message('error', 'Error sanitizing array data: ' . $e->getMessage());
log_message('error', 'Problematic data: ' . json_encode($data));
return $data; // Return the original data in case of error
}
}
}