FIX_EXCEL_SANTIZE_HELPER_IMPROVED

This commit is contained in:
Srinivas-Saravanan 2025-01-27 10:58:47 +05:30
parent 321ff9eb8d
commit 1f1f66cf3a

View File

@ -1,4 +1,5 @@
<?php
namespace App\Helpers;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
@ -6,17 +7,11 @@ use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
class ExcelSanitizeHelper
{
/**
* Array of non-printable characters to be removed from strings.
*
* You can modify this array to include any characters you want to remove.
* 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 $nonPrintableChars = [
"\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07", "\x08", "\x09",
"\x0A", "\x0B", "\x0C", "\x0D", "\x0E", "\x0F", "\x10", "\x11", "\x12", "\x13",
"\x14", "\x15", "\x16", "\x17", "\x18", "\x19", "\x1A", "\x1B", "\x1C", "\x1D",
"\x1E", "\x1F", "\x7F", "_x000D_", "_x000A_", "_x0009_", "_x0008_", "_x0007_",
"_x0006_", "_x0005_", "_x0004_", "_x0003_", "_x0002_", "_x0001_","\u200C"
];
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.
@ -24,22 +19,21 @@ class ExcelSanitizeHelper
* @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
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
$cleanData[$key] = trim(str_replace(self::$nonPrintableChars, '', $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