Jon
Jon

Reputation: 8521

Remove Whitespace Inside Array

I have an array where some of its elements are filled with lots of whitespace and \n. I would like to remove this whitespace and \n.

I have been using the following code, but the compiler says that my code does not work for arrays.

//My code that removes white-space    
$input = preg_replace( '/\s+/', ' ', $myArray);

//Sample of array with white space
$myArray = array(
    'extra spaces' => '<div>     </div>',
    'return' => '<b>\n</b>',
)

//What I want the array to look like
$myArray = array(
    'extra spaces' => '<div></div>',
    'return' => '<b></b>',
)

Upvotes: 0

Views: 107

Answers (3)

Oswald
Oswald

Reputation: 31647

  1. When you call preg_replace, $myArray is not yet defined. Switch the definition of $myArray and the call to preg_replace:

    //Sample of array with white space#
    
    $myArray = array(
        'extra spaces' => '<div>     </div>',
        'return' => '<b>\n</b>',
    )
    
    //My code that removes white-space    
    $input = preg_replace( '/\s+/', ' ', $myArray);
    
  2. If you want '<div> </div>' to become '<div></div>', you shouldn't replace '/\s+/' with ' ', but with ''.

  3. \n is considered a line break (and thus matches '/\s+/') only within double quotes, not within single quotes. Change '<b>\n</b>' to "<b>\n</b>" or fix your regular expression.

Upvotes: 1

Jochem Kuijpers
Jochem Kuijpers

Reputation: 1797

Try this:

// loop through each element and apply the function
foreach($myArray as $key => $value) {
    $myArray[$key] = preg_replace('/\s+/', '', $value);
}

Or make a function that does this and use array_walk

Note that I'm replacing your whitespace by an empty string, not by a single space (like you and other answers did). This way you will completely remove the whitespace, instead of replacing it with a space.

Upvotes: 1

Fluffeh
Fluffeh

Reputation: 33512

You can use a foreach loop to get through all the elements in your array:

foreach($myArray as $key => $val)
{
    $myArray[$key]=preg_replace( '/\s+/', ' ', $value);
}

I haven't actually checked the code, and haven't ever been good with regex, but assuming your replace works fine, it should be good.

Upvotes: 1

Related Questions