1. <?php
  2. /**
  3. * Limits the output of strings to prevent excessive data and aid in sandbox usage.
  4. *
  5. * @param string $string The string to limit.
  6. * @param int $maxLength The maximum length of the output string. Defaults to 100 characters.
  7. * @return string The limited string.
  8. */
  9. function limitStringOutput(string $string, int $maxLength = 100): string
  10. {
  11. // Use mb_substr for multi-byte string support.
  12. $limitedString = mb_substr($string, 0, $maxLength, 'UTF-8');
  13. // If the string is longer than the maximum length, add "..." to indicate truncation.
  14. if (mb_strlen($string, 'UTF-8') > $maxLength) {
  15. $limitedString .= "...";
  16. }
  17. return $limitedString;
  18. }
  19. // Example usage (for testing):
  20. $longString = "This is a very long string that needs to be limited for sandbox testing purposes. It should be truncated if it exceeds a certain length.";
  21. $limitedString = limitStringOutput($longString, 50);
  22. echo $limitedString . "\n"; // Output: This is a very long string that needs to be limited for sandbox testing purposes.
  23. $shortString = "Short string";
  24. $limitedShortString = limitStringOutput($shortString, 50);
  25. echo $limitedShortString . "\n"; //Output: Short string
  26. ?>

Add your comment