How to make an explode without returning empty values?

1

In PHP we can split a string and transform it into array .

Example:

$url = 'pagina/id/1';

explode('/', $url);

Result:

  

['page', 'id', '1']

However, if this url had a slash before and after, it would return some empty values.

$url = '/pagina/id/1/';

explode('/', $url);
  

['', 'page', 'id', '1', '']

How could you make sure these empty values are not returned (without having to array_filter )?

    
asked by anonymous 21.08.2015 / 18:36

6 answers

3

You can do this by using the preg_split function of PHP, which accepts some flags special for certain cases.

In this case, you will need to use flag PREG_SPLIT_NO_EMPTY

See:

preg_split('/\//', $url, -1, PREG_SPLIT_NO_EMPTY);

Result:

  

['page', 'id', '1']

Note : In this case, since preg_split uses regular expressions, it is necessary to escape some characters, or, alternatively, to use the preg_quote function.

Update : Remembering that preg_split with PREG_SPLIT_NO_EMPTY will remove all empty values from the result, including the "middle", as in /pagina//id//1 .

    
21.08.2015 / 18:36
2

It would be a good question if the question were to be without the use of regular expressions . I see no real reason to use ER in something that is so simple. There are several recommendations on the moderate use of ER's .

If the case is specific and the intent is simply to remove the / at the beginning and at the end to avoid creating empty indexes, then I would use the trim .

$url = explode( '/', trim( '/pagina/id/1/' , '/' ) );
print_r( $url );

// output
Array
(
    [0] => pagina
    [1] => id
    [2] => 1
)

Example on Ideone .

    
21.08.2015 / 18:50
2

It's not necessary to use regular expression, use array_diff() , I think it's the form shorter to do:

<?php
array_diff(explode('/', '/pagina//id//1'), array(''));

// resultado:
array (
  1 => 'pagina',
  3 => 'id',
  5 => '1',
);
    
21.08.2015 / 19:31
2

You can also get the same result with the function strtok ()

<?php

$str = "//pagina//id/1//";
$item = strtok($str,'/');
$arr[] = $item;

while($item = strtok('/')){
    $arr[] = $item;
}

echo "<pre>";
print_r($arr);

Example - ideonline

    
21.08.2015 / 19:51
1

Do a basic treatment before using explode() .

Below, an example with trim() and strpos()

$str = '/a/b/c/';
$str = trim($str, '/');
if( strpos( $str, '/' ) )
{
    $arr = explode('/',$str);
    print_r($arr);
}

/*
Array
(
    [0] => a
    [1] => b
    [2] => c
)
*/

Note that we are not considering a string with the $str = '/a//c/'; value that would result in

Array
(
    [0] => a
    [1] => 
    [2] => c
)

In this case, one must evaluate the business model, whether or not it allows empty values.

    
21.08.2015 / 19:56
0

You can use array_diff() :

$teste ='/a/b/c/d';

$saida = array_diff(explode('/', $teste), array('', null));

print_r($saida);
    
24.08.2015 / 17:37