Reputation: 1477
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
Reputation: 1477
I was able to fix this issue with $str = preg_replace('/[^(\x20-\x7F)]*/','', $str);
$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
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
Reputation: 68446
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);
Upvotes: 7
Reputation: 2128
Try this...
foreach ($array as $key=>$value)
{
if($value == '')
{
unset($array[$key]);
}
}
Upvotes: 1