PHP单文件实现代码去行首尾空格和去空行

当前位置: 电视猫 > php教程>
电视猫时间: 2024-07-09 11:55:06

  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:

  1. removeWhitespaceAndEmptyLines function:

    • Trim leading and trailing spaces: The trim() function is used to remove any leading and trailing spaces from the input string.
    • Replace multiple spaces: The 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 ().
    • Remove empty lines: Another 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).
  2. Example usage:

    • The $originalText variable holds the initial text with leading/trailing spaces and empty lines.
    • The removeWhitespaceAndEmptyLines() function is called with the $originalText to clean it.
    • The cleaned text is stored in the $cleanedText variable.
    • Finally, both the original and cleaned texts are printed for comparison.

Key points:

  • This code effectively removes leading and trailing spaces, replaces multiple spaces with a single space, and removes empty lines from the input string.
  • The preg_replace() function with regular expressions provides a powerful way to manipulate text based on patterns.
  • The example demonstrates how to use the function and shows the transformation of the text.
    最新电视剧
    热门电视剧
    影视资讯
    最新剧情排行榜
    最新电视剧剧情