1. <?php
  2. /**
  3. * Tokenizes input records for routine automation with fallback logic.
  4. *
  5. * @param string $record The input record string.
  6. * @param array $tokens An array to store the extracted tokens. Defaults to empty array.
  7. * @return array The array of extracted tokens.
  8. */
  9. function tokenizeRecord(string $record, array &$tokens = []): array
  10. {
  11. // Default fallback value if no tokens are found.
  12. if (empty($tokens)) {
  13. $tokens = [];
  14. }
  15. // Define potential token delimiters and patterns. Prioritize more specific patterns.
  16. $delimiters = [
  17. '/[\s,]+/', // Whitespace and commas
  18. '/=\s*/', // Equal sign followed by optional whitespace
  19. '/[:]/, // Colon
  20. ];
  21. $patterns = [
  22. 'key:value',
  23. 'key = value',
  24. 'key,value',
  25. 'value',
  26. ];
  27. // Iterate through the delimiters and patterns, trying each one until a match is found.
  28. foreach ($delimiters as $delimiter) {
  29. preg_match_all($delimiter, $record, $matches, PREG_SPLIT_NO_EMPTY); //Find all matches
  30. if (!empty($matches[0])) {
  31. foreach ($matches[0] as $match) {
  32. //Further processing of matches to extract key and value.
  33. $parts = explode('=', $match, 2); //Split at the first '='
  34. if (count($parts) == 2) {
  35. $key = trim($parts[0]);
  36. $value = trim($parts[1]);
  37. //Validation/Sanitization (add as needed)
  38. if (!empty($key) && !empty($value)) {
  39. $tokens[] = ['key' => $key, 'value' => $value];
  40. }
  41. } else {
  42. $tokens[] = ['value' => trim($match)]; //Treat as simple value if no '='
  43. }
  44. }
  45. return $tokens; //Return as soon as a successful tokenization is found
  46. }
  47. }
  48. // If no delimiters or patterns matched, treat the entire record as a single value.
  49. $tokens[] = ['value' => trim($record)];
  50. return $tokens;
  51. }
  52. //Example Usage
  53. //$record = "name=John Doe,age:30,city:New York";
  54. //$tokens = tokenizeRecord($record);
  55. //print_r($tokens);
  56. //$record = "John Doe";
  57. //$tokens = tokenizeRecord($record);
  58. //print_r($tokens);
  59. //$record = "key:value";
  60. //$tokens = tokenizeRecord($record);
  61. //print_r($tokens);
  62. ?>

Add your comment