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
- Trim the entire string first: This wipes out all leading and trailing whitespace (including those annoying initial empty lines, random spaces, or tabs).
- Split into lines: Use
explode("\n")to break the cleaned string into an array of individual lines. - Clean each line: Trim whitespace from every line to get rid of random spaces around your object names.
- 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
相关产品推荐
相关产品推荐

