|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Light\App\Service; |
| 6 | + |
| 7 | +use function preg_match; |
| 8 | +use function preg_match_all; |
| 9 | +use function preg_replace; |
| 10 | +use function trim; |
| 11 | + |
| 12 | +use const PREG_SET_ORDER; |
| 13 | + |
| 14 | +/** |
| 15 | + * Pulls the trailing `## FAQ` section (a `**Q: ...**` / `A: ...` pair per question) out of a |
| 16 | + * Markdown article body, so it can be rendered as an accordion and fed into JSON-LD separately |
| 17 | + * from the rest of the body. |
| 18 | + */ |
| 19 | +final class FaqExtractor |
| 20 | +{ |
| 21 | + /** |
| 22 | + * @return array{faq: list<array{question: string, answer: string}>, body: string} |
| 23 | + */ |
| 24 | + public static function extract(string $body): array |
| 25 | + { |
| 26 | + if (preg_match('/^## FAQ\s*$(.*)\z/ms', $body, $section, offset: 0) !== 1) { |
| 27 | + return ['faq' => [], 'body' => $body]; |
| 28 | + } |
| 29 | + |
| 30 | + $faq = []; |
| 31 | + preg_match_all( |
| 32 | + '/\*\*Q:\s*(.+?)\*\*\s*\n\s*A:\s*(.+?)(?=\n\s*\n|\z)/s', |
| 33 | + $section[1], |
| 34 | + $matches, |
| 35 | + PREG_SET_ORDER |
| 36 | + ); |
| 37 | + foreach ($matches as $match) { |
| 38 | + $faq[] = [ |
| 39 | + 'question' => trim($match[1]), |
| 40 | + 'answer' => trim(preg_replace('/\s+/', ' ', $match[2]) ?? ''), |
| 41 | + ]; |
| 42 | + } |
| 43 | + |
| 44 | + $body = trim((string) preg_replace('/^## FAQ\s*$.*\z/ms', '', $body)); |
| 45 | + |
| 46 | + return ['faq' => $faq, 'body' => $body]; |
| 47 | + } |
| 48 | +} |
0 commit comments