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.
《无所畏惧》温莉的结局是什么
时间:2023-11-25
《无所畏惧》刘铭的结局是什么
时间:2023-11-25
《无所畏惧》罗英子和陈硕最后在一起了吗
时间:2023-11-25
《宁安如梦》 姜雪宁是如何设计让薛姝去和亲
时间:2023-11-25
《宁安如梦》薛姝为了不和亲做了什么
时间:2023-11-25
《宁安如梦》为什么姜雪蕙只能当侧妃
时间:2023-11-25