Plain Text Cleaner
Cleans plain text without destroying legitimate punctuation, accents, or line breaks.
Function signature
ogCleanPlainText(text, max_length = 5000, allow_line_breaks = true)
Categories
- Content Display
Parameters
textRaw plain text.max_lengthMaximum allowed length after cleaning. Use 0 for no cap.allow_line_breaksWhether to preserve line breaks.Return value
Short public-safe status message.
- text
- length
- truncated
Compatibility
Existing function name and call order preserved; metadata signature corrected to source.
Minimum PHP version: 7.4
Security notes
Validate request method, identity, permissions, and caller-owned allowlists before use; keep secrets and internal paths out of public output.
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Cleans plain text while preserving normal punctuation, accents, and allowed line breaks.
*
* @param string $text Raw plain text.
* @param int $max_length Maximum allowed length after cleaning. Use 0 for no cap.
* @param bool $allow_line_breaks Whether to preserve line breaks.
* @return array Cleaned text result.
*/
function ogCleanPlainText($text, $max_length = 5000, $allow_line_breaks = true) {
$result = array(
'success' => false,
'message' => '',
'data' => array()
);
$text = (string)$text;
$max_length = (int)$max_length;
$allow_line_breaks = (bool)$allow_line_breaks;
$text = str_replace("\0", '', $text);
$text = strip_tags($text);
$text = str_replace(array("\r\n", "\r"), "\n", $text);
if (!$allow_line_breaks) {
$text = preg_replace('/\s+/', ' ', $text);
} else {
$text = preg_replace('/[\t ]+/', ' ', $text);
$text = preg_replace('/\n{3,}/', "\n\n", $text);
}
$text = trim($text);
$was_truncated = false;
if ($max_length > 0 && strlen($text) > $max_length) {
$text = substr($text, 0, $max_length);
$text = rtrim($text);
$was_truncated = true;
}
$result['success'] = true;
$result['message'] = 'Plain text cleaned.';
$result['data'] = array(
'text' => $text,
'length' => strlen($text),
'was_truncated' => $was_truncated
);
return $result;
}