1. <?php
  2. /**
  3. * Flags anomalies in text blocks for validation checks with fallback logic.
  4. *
  5. * @param string $text The text block to analyze.
  6. * @param array $config Configuration array.
  7. * - 'keywords' => array of keywords to look for (anomalous indicators).
  8. * - 'length_threshold' => minimum/maximum length for flagging.
  9. * - 'pattern' => Regular expression for specific pattern detection.
  10. * - 'fallback_validation' => Callback function for additional validation.
  11. * @return array An array containing:
  12. * - 'anomalous' => boolean - True if anomalies are detected, false otherwise.
  13. * - 'reason' => string - Explanation of why anomalies were detected (if applicable).
  14. * - 'flagged_text' => string - The original text block.
  15. */
  16. function flagTextAnomalies(string $text, array $config): array
  17. {
  18. $anomalous = false;
  19. $reason = '';
  20. $flagged_text = $text;
  21. // Keyword check
  22. if (isset($config['keywords']) && is_array($config['keywords'])) {
  23. foreach ($config['keywords'] as $keyword) {
  24. if (stripos($flagged_text, $keyword) !== false) {
  25. $anomalous = true;
  26. $reason .= "Keyword found: " . $keyword . "\n";
  27. }
  28. }
  29. }
  30. // Length check
  31. if (isset($config['length_threshold']) && is_array($config['length_threshold'])) {
  32. $min_length = $config['length_threshold'][0];
  33. $max_length = $config['length_threshold'][1];
  34. if (strlen($flagged_text) < $min_length || strlen($flagged_text) > $max_length) {
  35. $anomalous = true;
  36. $reason .= "Length outside range: " . $min_length . "-" . $max_length . "\n";
  37. }
  38. }
  39. // Pattern check
  40. if (isset($config['pattern']) && is_string($config['pattern'])) {
  41. if (preg_match($config['pattern'], $flagged_text)) {
  42. $anomalous = true;
  43. $reason .= "Pattern detected: " . $config['pattern'] . "\n";
  44. }
  45. }
  46. // Fallback validation
  47. if (isset($config['fallback_validation']) && is_callable($config['fallback_validation'])) {
  48. $fallback_result = $config['fallback_validation']($flagged_text);
  49. if ($fallback_result) {
  50. $anomalous = true;
  51. $reason .= "Fallback validation failed.\n";
  52. }
  53. }
  54. return [
  55. 'anomalous' => $anomalous,
  56. 'reason' => $reason,
  57. 'flagged_text' => $flagged_text,
  58. ];
  59. }
  60. ?>

Add your comment