<?php
/**
* Flags anomalies in text blocks for validation checks with fallback logic.
*
* @param string $text The text block to analyze.
* @param array $config Configuration array.
* - 'keywords' => array of keywords to look for (anomalous indicators).
* - 'length_threshold' => minimum/maximum length for flagging.
* - 'pattern' => Regular expression for specific pattern detection.
* - 'fallback_validation' => Callback function for additional validation.
* @return array An array containing:
* - 'anomalous' => boolean - True if anomalies are detected, false otherwise.
* - 'reason' => string - Explanation of why anomalies were detected (if applicable).
* - 'flagged_text' => string - The original text block.
*/
function flagTextAnomalies(string $text, array $config): array
{
$anomalous = false;
$reason = '';
$flagged_text = $text;
// Keyword check
if (isset($config['keywords']) && is_array($config['keywords'])) {
foreach ($config['keywords'] as $keyword) {
if (stripos($flagged_text, $keyword) !== false) {
$anomalous = true;
$reason .= "Keyword found: " . $keyword . "\n";
}
}
}
// Length check
if (isset($config['length_threshold']) && is_array($config['length_threshold'])) {
$min_length = $config['length_threshold'][0];
$max_length = $config['length_threshold'][1];
if (strlen($flagged_text) < $min_length || strlen($flagged_text) > $max_length) {
$anomalous = true;
$reason .= "Length outside range: " . $min_length . "-" . $max_length . "\n";
}
}
// Pattern check
if (isset($config['pattern']) && is_string($config['pattern'])) {
if (preg_match($config['pattern'], $flagged_text)) {
$anomalous = true;
$reason .= "Pattern detected: " . $config['pattern'] . "\n";
}
}
// Fallback validation
if (isset($config['fallback_validation']) && is_callable($config['fallback_validation'])) {
$fallback_result = $config['fallback_validation']($flagged_text);
if ($fallback_result) {
$anomalous = true;
$reason .= "Fallback validation failed.\n";
}
}
return [
'anomalous' => $anomalous,
'reason' => $reason,
'flagged_text' => $flagged_text,
];
}
?>
Add your comment