|null */ public function parse(string $text): ?array { $text = trim(str_replace(["\r\n", "\r", "\u{3000}"], ["\n", "\n", ' '], $text)); if ($text === '') { return null; } if (class_exists(\Normalizer::class)) { $text = \Normalizer::normalize($text, \Normalizer::FORM_KC) ?: $text; } $text = preg_replace('/(?<=\d)\.\s+(?=\d{2})/u', '.', $text) ?? $text; $invoiceNumber = $this->invoiceNumber($text); $invoiceTotal = $this->invoiceTotal($text); if ($invoiceNumber === '' || $invoiceTotal <= 0 || ! in_array(strlen($invoiceNumber), [8, 20], true)) { return null; } $taxNumbers = []; $taxPatterns = [ '/(?:统一社会信用代码|纳税人识别号|税号)[^\nA-Z0-9]{0,16}([0-9A-Z]{15,20})/u', '/(?format('Y-m-d'); } catch (Throwable) { $invoiceDate = null; } } if ($invoiceDate === null && preg_match('/(?format('Y-m-d'); } catch (Throwable) { $invoiceDate = null; } } $items = []; if (preg_match_all('/^\s*(\*[^\n]{2,180})$/mu', $text, $matches)) { $items = array_values(array_unique(array_map('trim', $matches[1]))); } $taxRate = ''; if (preg_match('/(\d{1,2}(?:\.\d+)?%|免税|不征税|\*)/u', $text, $matches)) { $taxRate = $matches[1]; } return [ 'is_invoice' => true, 'invoice_type' => $this->invoiceType($text), 'seller_name' => $names[1] ?? '', 'seller_tax_no' => $taxNumbers[1] ?? '', 'buyer_name' => $names[0] ?? '', 'buyer_tax_no' => $taxNumbers[0] ?? '', 'invoice_total' => $invoiceTotal, 'invoice_number' => $invoiceNumber, 'invoice_date' => $invoiceDate, 'item_name' => implode("\n", $items), 'amount_without_tax' => null, 'tax_rate' => $taxRate, 'tax_amount' => null, 'ocr_text' => $text, ]; } private function invoiceNumber(string $text): string { foreach ([ '/发票号码\s*[::]?\s*([0-9A-Z][0-9A-Z ::]{7,40})/u', '/发[买米来][号玛码]?\s*[::]?\s*([0-9A-Z][0-9A-Z ::]{7,40})/u', '/(?= 8) { return $number; } } } if ((str_contains($text, '发票号码') || str_contains($text, '定额发票')) && preg_match('/(? round((float) str_replace(',', '', $value), 2), $matches[1], ); return max($values); } } if (str_contains($text, '发票') && preg_match_all('/[¥¥]\s*([0-9][0-9,]*\.[0-9]{2})/u', $text, $matches) && $matches[1] !== []) { return max(array_map( static fn (string $value): float => round((float) str_replace(',', '', $value), 2), $matches[1], )); } return 0.0; } private function invoiceType(string $text): string { if (str_contains($text, '铁路电子客票') || str_contains($text, '铁路客票')) { return '电子发票(铁路电子客票)'; } if (str_contains($text, '增值税专用发票') || str_contains($text, '专用发票')) { return '电子发票(增值税专用发票)'; } if (str_contains($text, '普通发票')) { return '电子发票(普通发票)'; } return '其他'; } }