PHP code example of watheqalshowaiter / quran-validator

1. Go to this page and download the library: Download watheqalshowaiter/quran-validator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

watheqalshowaiter / quran-validator example snippets


use Watheq\QuranValidator\LlmIntegration;

$systemPrompt = LlmIntegration::SYSTEM_PROMPTS['xml']
    ."\n\n"
    .$yourOtherInstructions;

// The LLM should now output Quran quotes like:
// <quran ref="1:1">بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ</quran>

use Watheq\QuranValidator\LlmIntegration;

$processor = LlmIntegration::create();
$result = $processor->process($llmResponse);

if (!$result->allValid()) {
    $invalid = array_filter(
        $result->quotes(),
        static fn ($quote): bool => !$quote->isValid(),
    );
}

echo $result->correctedText();

foreach ($result->quotes() as $quote) {
    $status = $quote->isValid() ? 'valid' : 'invalid';
    echo "{$quote->reference}: {$status} ({$quote->detectionMethod})\n";
}

foreach ($result->warnings() as $warning) {
    echo $warning."\n";
    // Untagged Quran quote detected: "قُلْ هُوَ..." (112:1)
}

use Watheq\QuranValidator\QuranValidator;

$validator = QuranValidator::fromDefaultDataset();
$result = $validator->validate('بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ');

var_dump($result->isValid());   // true
echo $result->reference();      // 1:1
echo $result->matchType();      // exact, normalized, or none

if ($result->matchType() !== 'exact' && $result->matchedVerse() !== null) {
    echo $result->matchedVerse()->text;
}

$result = $validator->validateAgainst('بسم الله', '1:1');

if (!$result->isValid()) {
    echo "Expected: {$result->expectedNormalized}\n";
    echo "Got: {$result->normalizedInput}\n";
    echo "Mismatch at index: {$result->mismatchIndex}\n";
}

$range = $validator->getVerseRange(112, 1, 4);

if ($range !== null) {
    echo $range['text'];
    foreach ($range['verses'] as $verse) {
        echo $verse->reference()."\n";
    }
}

// String references are also supported:
$verses = $validator->range('112:1-4');

$analysis = $validator->analyzeFabrication('بسم الله الفلان');

foreach ($analysis->words as $word) {
    $status = $word->fabricated ? 'fabricated' : 'valid';
    echo "{$word->word}: {$status}\n";
}

echo $analysis->stats->fabricatedRatio;

use Watheq\QuranValidator\LlmIntegration;

LlmIntegration::SYSTEM_PROMPTS['xml'];
// <quran ref="1:1">...</quran>

LlmIntegration::SYSTEM_PROMPTS['markdown'];
// A fenced quran code block with a reference

LlmIntegration::SYSTEM_PROMPTS['bracket'];
// [[Q:1:1|...]]

LlmIntegration::SYSTEM_PROMPTS['minimal'];
// ... (1:1)

use Watheq\QuranValidator\LlmIntegration;
use Watheq\QuranValidator\ValueObjects\LlmIntegrationOptions;

$processor = LlmIntegration::create(new LlmIntegrationOptions(
    autoCorrect: true,
    scanUntagged: true,
    tagFormat: 'xml',
));

use Watheq\QuranValidator\LlmIntegration;

$result = LlmIntegration::quickValidate($llmResponse);

var_dump($result['has_quran_content']);
var_dump($result['all_valid']);
print_r($result['issues']);

$verse = $validator->getVerse(2, 255);
echo $verse?->text;

$surah = $validator->getSurah(1);
echo $surah?->englishName;  // Al-Fatiha
echo $surah?->versesCount;  // 7

$results = $validator->search('الرحمن الرحيم', limit: 5);
foreach ($results as $result) {
    $verse = $result['verse'];
    printf("%s (%.2f)\n", $verse->reference(), $result['similarity']);
}

use Watheq\QuranValidator\ArabicNormalizer;

$normalizer = new ArabicNormalizer();

$normalizer->normalize('السَّلَامُ عَلَيْكُمُ'); // السلام عليكم
$normalizer->removeDiacritics('بِسْمِ اللَّهِ'); // بسم الله
$normalizer->containsArabic('Hello مرحبا world'); // true

$segments = $normalizer->extractArabicSegments('Say بسم الله and continue');
foreach ($segments as $segment) {
    echo "{$segment->text}: {$segment->start}-{$segment->end}\n";
}

use Watheq\QuranValidator\LlmIntegration;

function validateLlmResponse(string $response): string
{
    $result = LlmIntegration::create()->process($response);

    if ($result->hasErrors()) {
        throw new RuntimeException('The response contains an invalid Quran quotation.');
    }

    return $result->correctedText();
}