madhushankarox
madhushankarox

Reputation: 1477

Removing white-spaces / empty values from a PHP array

I'm developing a word counting application and I'm using following code to load words to an array.

$str = ' Some string is here     ...  Another string.. ';
$str = trim($str);
$str = preg_replace('/\s+/', ' ', $str);
$str_array = explode(" ", $str);
$str_array = array_filter($str_array);

But the issue is I'm getting empty values in my array like follows.

Array
(
    [0] => Word1
    [1] => Word2
    [2] => Word3
    [3] => 
    [4] => 
    [5] => 
)

I've tried array_filter($str_array) and more stackoverflow answers. But I was failed to get this done. Can some one please help me to fix this issue? Thanks!

Upvotes: 3

Views: 3472

Answers (4)

madhushankarox
madhushankarox

Reputation: 1477

I was able to fix this issue with $str = preg_replace('/[^(\x20-\x7F)]*/','', $str);

Source

        $str = strip_tags($str);
        $str = trim($str);
        $str = preg_replace('/ HYPERLINK "[^"]*" /', '', $str);
        $str = preg_replace('/\s+/', ' ', $str);
        $str = preg_replace('/[^(\x20-\x7F)]*/','', $str);

Upvotes: 0

user2706194
user2706194

Reputation: 199

$str = ' Some string is here     ...  Another string.. ';
$str = trim($str);
$str = str_replace('  ', ' ', $str); //replace two space to single space
$str_array = explode(" ", $str);

Upvotes: 0

Trim the array elements using trim by array_map and finally do an array_filter using strlen as the call-back.

<?php
$arr=Array
(
    0 => 'Word1',
    1 => 'Word2',
    2 => 'Word3',
    3 => ' ',
    4 => '',
    5 => ''
);

$new_arr = array_filter(array_map('trim',$arr),'strlen');
print_r($new_arr);

Demo

Upvotes: 7

Nishant Solanki
Nishant Solanki

Reputation: 2128

Try this...

 foreach ($array as $key=>$value) 
 { 
     if($value == '')
     {
       unset($array[$key]);
     }
 }

Upvotes: 1

Related Questions