You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP:如何拆分带换行字符串并清除空行与多余空格?

How to Clean Your String into a Usable Array

Got it, let's tackle this problem head-on. The issue with your current explode("\n", $output) approach is that it’ll include those messy leading empty lines as empty array elements, plus each object line might still have random leading/trailing spaces cluttering things up. Here’s a straightforward, step-by-step fix:

Step-by-Step Solution

  1. Trim the entire string first: This wipes out all leading and trailing whitespace (including those annoying initial empty lines, random spaces, or tabs).
  2. Split into lines: Use explode("\n") to break the cleaned string into an array of individual lines.
  3. Clean each line: Trim whitespace from every line to get rid of random spaces around your object names.
  4. Filter out empty lines: Remove any leftover empty entries (in case there were blank lines scattered between your objects).

Example Code

Here’s how to put it all together concisely:

// Your original messy string
$output = "


    Object One
Object Two  
  Object Three
Object Four
Object Five
Object Six    

";

// Clean and convert to usable array
$cleanArray = array_filter(
    array_map('trim', explode("\n", trim($output))),
    function($item) {
        return $item !== '';
    }
);

// Test the result
print_r($cleanArray);

What Each Part Does:

  • trim($output): Eliminates all leading/trailing whitespace (goodbye, those initial empty lines!).
  • explode("\n", ...): Splits the trimmed string into an array where each element is a single line.
  • array_map('trim', ...): Trims extra spaces from every line (so " Object Three" becomes "Object Three").
  • array_filter(...): Removes any empty strings that might linger (like if there were blank lines between objects).

Shorter Version (PHP 7.4+)

If you’re on PHP 7.4 or newer, arrow functions make this even cleaner:

$cleanArray = array_filter(array_map('trim', explode("\n", trim($output))), fn($item) => $item !== '');

Final Result

Running this code will give you a spotless array:

Array
(
    [0] => Object One
    [1] => Object Two
    [2] => Object Three
    [3] => Object Four
    [4] => Object Five
    [5] => Object Six
)

内容的提问来源于stack exchange,提问作者Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:08:51