102 lines
3.2 KiB
PHP
102 lines
3.2 KiB
PHP
<?php
|
|
namespace app\admin\addresmart;
|
|
|
|
class AppointmentParser
|
|
{
|
|
public function parse(string $text): ?array
|
|
{
|
|
if ($this->isFormatA($text)) {
|
|
return $this->extractFormatA($text);
|
|
}
|
|
|
|
if ($this->isFormatB($text)) {
|
|
return $this->extractFormatB($text);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
// --- Format A ---
|
|
private function isFormatA(string $text): bool
|
|
{
|
|
$requiredFields = ['姓名:', '电话:', '地址:', '日期:', '时间:', '商品名称:'];
|
|
foreach ($requiredFields as $field) {
|
|
if (mb_strpos($text, $field) === false) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
private function extractFormatA(string $text): array
|
|
{
|
|
$date = $this->match('/日期:(\d{4}-\d{2}-\d{2})/', $text);
|
|
$timeRange = $this->match('/时间:([\d:]+)~[\d:]+/', $text);
|
|
$datetime = $date && $timeRange ? "$date $timeRange" : null;
|
|
|
|
// 提取电话号码和分机号
|
|
$phoneMatches = [];
|
|
preg_match('/电话:.*?(\d{11})[^\d]{0,5}(\d{3,5})?/u', $text, $phoneMatches);
|
|
$phone = $phoneMatches[1] ?? null;
|
|
$ext = $phoneMatches[2] ?? null;
|
|
|
|
return [
|
|
'name' => $this->match('/姓名:(.+)/u', $text),
|
|
'phone' => $phone,
|
|
'ext' => $ext,
|
|
'address' => $this->match('/地址:(.+)/u', $text),
|
|
'date' => $date,
|
|
'time' => $timeRange,
|
|
'datetime' => $datetime,
|
|
'project' => $this->match('/商品名称:(.+)/u', $text),
|
|
];
|
|
}
|
|
|
|
|
|
|
|
// --- Format B ---
|
|
private function isFormatB(string $text): bool
|
|
{
|
|
$requiredFields = ['预约项目:', '预约地址:', '联系人:', '联系电话:', '预约时间:'];
|
|
foreach ($requiredFields as $field) {
|
|
if (mb_strpos($text, $field) === false) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
private function extractFormatB(string $text): array
|
|
{
|
|
$date = $this->match('/预约时间:(\d{4}-\d{2}-\d{2})/', $text);
|
|
$timeRange = $this->match('/预约时间:\d{4}-\d{2}-\d{2} ([\d:]+)-[\d:]+/', $text);
|
|
$datetime = $date && $timeRange ? "$date $timeRange" : null;
|
|
|
|
// 提取电话号码和分机号
|
|
$phoneMatches = [];
|
|
preg_match('/联系电话:.*?(\d{11})(?:\D{0,5}(\d{3,5}))?/u', $text, $phoneMatches);
|
|
$phone = $phoneMatches[1] ?? null;
|
|
$ext = $phoneMatches[2] ?? null;
|
|
|
|
return [
|
|
'name' => $this->match('/联系人:([^\n]+)/u', $text),
|
|
'phone' => $phone,
|
|
'ext' => $ext,
|
|
'address' => $this->match('/预约地址:(.+)/u', $text),
|
|
'date' => $date,
|
|
'time' => $timeRange,
|
|
'datetime' => $datetime,
|
|
'project' => $this->match('/预约项目:(.+)/u', $text),
|
|
];
|
|
}
|
|
|
|
// --- 通用正则匹配 ---
|
|
private function match(string $pattern, string $text): ?string
|
|
{
|
|
if (preg_match($pattern, $text, $matches)) {
|
|
return trim($matches[1]);
|
|
}
|
|
return null;
|
|
}
|
|
}
|