PHP单文件实现代码去行首尾空格和去空行
Sure, here is a single-file PHP code to remove leading and trailing spaces and empty lines from a string:
PHP
<?php
function removeWhitespaceAndEmptyLines($text) {
// Remove leading and trailing spaces
$text = trim($text);
// Replace multiple consecutive spaces with a single space
$text = preg_replace('/\s+/', ' ', $text);
// Remove empty lines
$text = preg_replace('/(\n|\r)+/', "\n", $text);
return $text;
}
// Example usage
$originalText = " This is a string with leading and trailing spaces, \n\n and empty lines. \n";
$cleanedText = removeWhitespaceAndEmptyLines($originalText);
echo "Original text:\n" . $originalText . "\n\n";
echo "Cleaned text:\n" . $cleanedText;
Explanation:
removeWhitespaceAndEmptyLines
function:
trim()
function is used to remove any leading and trailing spaces from the input string.preg_replace()
function is used to replace multiple consecutive spaces with a single space. This regular expression matches one or more spaces (\s+
) and replaces them with a single space ().preg_replace()
call is used to remove empty lines. This regular expression matches one or more newline characters (\n|\r
) and replaces them with a single newline character (\n
).Example usage:
$originalText
variable holds the initial text with leading/trailing spaces and empty lines.removeWhitespaceAndEmptyLines()
function is called with the $originalText
to clean it.$cleanedText
variable.Key points:
preg_replace()
function with regular expressions provides a powerful way to manipulate text based on patterns.