Skip to content

AI Text Summarizer — PHP source

Paste any text and get an LLM summary — TL;DR, bullets, or detailed — using your own free Groq key, called straight from your browser.

This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.

<?php
/**
 * text-summarizer - prompt building, reply cleanup, and text stats.
 *
 * Language: PHP 7.4+ (standard library only).
 * CosmoDev polyglot showcase port of the `text-summarizer` tool, ported from
 * src/lib/summarize.ts (the canonical TypeScript implementation).
 *
 * PCRE with the /u flag carries the TS lib's two tiny regexes, so this is a
 * near-transliteration. `chars` counts UTF-16 code units - JS `.length`
 * semantics - by summing code points plus one per astral (U+10000+) point.
 *
 * display source - part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

/** Input cap: longer pastes are cut (and marked) before they reach the model. */
const MAX_INPUT_CHARS = 12000;

/** Per-style system-prompt contract, byte-for-byte the TS lib's STYLE_CONTRACT. */
const STYLE_CONTRACT = [
    'tldr' => 'Summarize the text as ONE sentence of at most 25 words. Plain text, no preamble, no bullets.',
    'bullets' => 'Summarize the text as 3 to 6 markdown bullets, each starting with "- " and covering one distinct point. No preamble, no closing remark.',
    'detailed' => 'Summarize the text as 2 to 4 short paragraphs: what it is about, the key facts, and the outcome or next step. No preamble, no headings.',
];

/**
 * Count words / sentences / characters; tolerant of empty input.
 *
 * Words are the non-empty whitespace-run tokens (PREG_SPLIT_NO_EMPTY turns
 * empty / whitespace-only input into [], the 0 the TS ternary yields).
 * Sentences count TERMINATOR runs ([.!?]+), not bodies - the body regex is
 * quadratic on terminator-free input, the trap the TS lib documents. chars
 * counts UTF-16 code units: code points plus one extra per astral point.
 *
 * @return array{words: int, sentences: int, chars: int}
 */
function text_stats(string $text): array
{
    preg_match_all('/[.!?]+/', $text, $terminators);
    preg_match_all('/./us', $text, $points);
    preg_match_all('/[\x{10000}-\x{10FFFF}]/u', $text, $astral);
    $words = preg_split('/\s+/u', $text, -1, PREG_SPLIT_NO_EMPTY);

    return [
        'words' => count($words),
        'sentences' => count($terminators[0]),
        'chars' => count($points[0]) + count($astral[0]),
    ];
}

/**
 * Slice the first $limit UTF-16 code units off $text, mirroring JS slice:
 * the budget is counted in code units but the cut lands between points
 * (an astral character straddling the boundary loses its orphan half).
 */
function cut_utf16(string $text, int $limit): string
{
    $units = 0;
    $out = '';
    foreach (preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY) as $point) {
        preg_match('/[\x{10000}-\x{10FFFF}]/u', $point, $hit);
        $width = $hit ? 2 : 1;
        if ($units + $width > $limit) {
            break;
        }
        $out .= $point;
        $units += $width;
    }

    return $out;
}

/**
 * Build the [system, user] chat messages for the provider layer; pastes past
 * MAX_INPUT_CHARS are cut (in UTF-16 units, like JS slice) with a marker.
 *
 * @param string $style One of the STYLE_CONTRACT keys.
 *
 * @return array<int, array{role: string, content: string}>
 *
 * @throws \InvalidArgumentException on a style outside the contract (the TS
 * union type makes that state unrepresentable; PHP throws instead).
 */
function build_prompt_messages(string $text, string $style): array
{
    if (!isset(STYLE_CONTRACT[$style])) {
        throw new InvalidArgumentException("unknown style: {$style}");
    }

    $stats = text_stats($text);
    $body = $stats['chars'] > MAX_INPUT_CHARS
        ? cut_utf16($text, MAX_INPUT_CHARS) . "\n… (text truncated)"
        : $text;

    return [
        ['role' => 'system', 'content' => 'You summarize text faithfully. ' . STYLE_CONTRACT[$style]],
        ['role' => 'user', 'content' => "Summarize the following text ({$style} style; {$stats['words']} words, {$stats['sentences']} sentences).\n\n{$body}"],
    ];
}

/**
 * Clean the model's reply into displayable summary text - any non-empty
 * cleaned text is the summary; null only when nothing survives. JS trim()
 * removes Unicode whitespace, so trim via \s+u rather than PHP's ASCII trim.
 */
function parse_summary(string $text): ?string
{
    $unfenced = preg_replace('/```[a-z]*\n?/', '', $text) ?? '';
    $cleaned = preg_replace('/^\s+|\s+$/u', '', $unfenced) ?? '';

    return $cleaned !== '' ? $cleaned : null;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →