AI Text Translator — PHP source
Translate any text between 24 languages with an LLM — auto-detected or explicit source, straight from your browser with your own free Groq key.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* text-translator — AI text translator: prompt building + reply cleanup.
*
* Language: PHP 7.4+ (standard library only).
* CosmoDev polyglot showcase port of the `text-translator` tool, ported from
* src/lib/translate.ts (the canonical TypeScript implementation).
*
* Why this file exists: the translator island is a thin shell over a shared
* LLM provider, so the portable, testable surface is pure — the curated
* language list, the [system, user] chat-message construction, and the reply
* cleanup that strips stray markdown fences via one preg_replace.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
declare(strict_types=1);
/** Source-language sentinel: let the model detect the input language. */
const AUTO_SOURCE = 'auto';
/** Sentinel entry shown in the "from" select. */
const AUTO_LANGUAGE = ['id' => AUTO_SOURCE, 'label' => 'Auto-detect'];
/** Curated common-language list — the single source of truth for both selects. */
const LANGUAGES = [
['id' => 'en', 'label' => 'English'],
['id' => 'es', 'label' => 'Spanish'],
['id' => 'fr', 'label' => 'French'],
['id' => 'de', 'label' => 'German'],
['id' => 'pt', 'label' => 'Portuguese'],
['id' => 'it', 'label' => 'Italian'],
['id' => 'nl', 'label' => 'Dutch'],
['id' => 'sv', 'label' => 'Swedish'],
['id' => 'pl', 'label' => 'Polish'],
['id' => 'tr', 'label' => 'Turkish'],
['id' => 'ru', 'label' => 'Russian'],
['id' => 'uk', 'label' => 'Ukrainian'],
['id' => 'ar', 'label' => 'Arabic'],
['id' => 'fa', 'label' => 'Persian'],
['id' => 'he', 'label' => 'Hebrew'],
['id' => 'hi', 'label' => 'Hindi'],
['id' => 'bn', 'label' => 'Bengali'],
['id' => 'zh', 'label' => 'Chinese'],
['id' => 'ja', 'label' => 'Japanese'],
['id' => 'ko', 'label' => 'Korean'],
['id' => 'vi', 'label' => 'Vietnamese'],
['id' => 'th', 'label' => 'Thai'],
['id' => 'id', 'label' => 'Indonesian'],
['id' => 'sw', 'label' => 'Swahili'],
];
const MAX_INPUT_CHARS = 12000;
/** Label for a known language id; unknown ids pass through unchanged. */
function language_label(string $id): string
{
foreach (LANGUAGES as $language) {
if ($language['id'] === $id) {
return $language['label'];
}
}
return $id;
}
/**
* Build the [system, user] chat messages for the provider layer.
*
* Returns a list of ['role' => 'system'|'user', 'content' => ...] maps.
* $from is AUTO_SOURCE or a LANGUAGES id; $to is a LANGUAGES id. Inputs
* longer than MAX_INPUT_CHARS are cut and marked so the model knows the
* text ends early (mb_strlen counts code points; the TS slice counts
* UTF-16 code units).
*
* @return list<array{role: string, content: string}>
*/
function build_prompt_messages(string $text, string $from, string $to): array
{
$fromPart = $from === AUTO_SOURCE
? 'Detect the source language yourself.'
: 'The source language is ' . language_label($from) . '.';
$body = $text;
if (mb_strlen($text) > MAX_INPUT_CHARS) {
$body = mb_substr($text, 0, MAX_INPUT_CHARS) . "\n… (text truncated)";
}
return [
[
'role' => 'system',
'content' => 'You are a faithful translator. ' . $fromPart
. ' Translate the user\'s text into ' . language_label($to)
. '. Output ONLY the translation — no preamble, no notes, no backticks, preserving paragraphs, formatting, and code blocks as-is.',
],
['role' => 'user', 'content' => $body],
];
}
/**
* Clean the model's reply into displayable translation text. No strict
* format contract — any non-empty cleaned text is the translation; null
* only when nothing survives. preg_replace is global by default, so this
* mirrors the TS port's /```[a-z]*\n?/g.
*/
function parse_translation(string $text): ?string
{
$cleaned = trim((string) preg_replace('/```[a-z]*\n?/', '', $text));
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 →