I’m working with an API that sends me a string of information, separated by an undefined number of spaces. When I try exploding it, I end up with some elements composed solely of spaces. I’ve tried using a foreach, preg_replace, preg_match, pretty much everything I could find to get rid of these spaces, but there are still some left, The strange thing is, even if I replace these spaces with another symbol and then explode the string and remove the elements composed only of this symbol, the space-only elements remain. Also, any method of removing them removes some, but there’s usually 2 or 3 that remain between each array position that contains useful information.
Example: I recieve a string that looks something like this (I’m using // to separate elements):
// // // // // // // // // //1000 // // // // // // // // // // // //0
// // // // // // // //1 // // // // // // // //1 // // // //101 // //
// // // // // //272 // // // // // // // //ubuntu-10.04-x86 // // //
//basic // // // // // // // //true // // // //running // // // //0 //
// // // // // // // // // // //1000 // // // // // // // // // // //
//0 // // // // // // // //1 // // // // // // // //2 // // // //102
// // // // // // // //272 // // // // // // // //ubuntu-10.04-x86 //
// // //basic // // // // // // // //true // // // //running // // //
//0 // // // // // // // // // // // //1000 // // // // // // // // //
// // //0 // // // // // // // //1 // // // // // // // //3 // // //
//103 // // // // // // // //0 // // // // // // // //ubuntu-10.04-x86
// // // //vswap-256m // // // // // // // //false // // // //stopped
// // // // // // //
When I do
$result = preg_replace('/\s[\s]+/', '-', $result);
$result = preg_split('~-~', $result, -1, PREG_SPLIT_NO_EMPTY);
foreach($result as $item){
echo "$item //";
}
for example, I end up with this:
// // //1000 // // //0 // //1 // //1 //101 // //272 // //ubuntu
//10.04 //x86 //basic // //true //running //0 // // // //1000 // //
//0 // //1 // //2 //102 // //272 // //ubuntu //10.04 //x86 //basic //
//true //running //0 // // // //1000 // // //0 // //1 // //3 //103 //
//0 // //ubuntu //10.04 //x86 //vswap //256m // //false //stopped //
// //
Anyone know how I can get rid of those empty elements from the array?
You can use array_filter to filter out elements according to your own criteria.