How to make a explode without returning empty values?

Asked

Viewed 392 times

1

In PHP we can split one string and turn it into array.

Example:

$url = 'pagina/id/1';

explode('/', $url);

Upshot:

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

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

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

explode('/', $url);

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

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

6 answers

3


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

In such cases, the flag PREG_SPLIT_NO_EMPTY

Behold:

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

Upshot:

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

Observing: In that case, how preg_split uses regular expressions, it is necessary to escape some characters, or alternatively use the function preg_quote.

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

  • 2

    another limiter can be used for preg instead of using / as a limiter can be used #, @, ~, getting ~/~, #/#, @/@

2

It would be a good question if the question were 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 intention is simply to remove the / at the beginning and at the end to avoid creating empty indexes, so I would make use of the function trim.


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

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

Example in Ideone.

  • I agree that regular expressions in some cases are bad, but you agree with me that your code would have problems if the user passed the following expression at the url 'pagina//id//1' ? The trim only serves to clear the end and start. In the case of PREG_SPLIT_NO_EMPTY he would eliminate anything that was empty

  • 1

    array_filter clears empty url indexes pagina//id//1. Aind dwarf see reason for ER at url ``'pagina//id//1'`.

  • If I used the old one you made with pagina//id//1, would return that array(5) {
 [0] =>
 string(6) "pagina"
 [1] =>
 string(0) ""
 [2] =>
 string(2) "id"
 [3] =>
 string(0) ""
 [4] =>
 string(1) "1"
}


  • You think it would be a gain to use array_filter(explode()) instead of preg_split (it’s not a sarcastic question, it’s sincere) ?

  • I don’t like url that accepts multiple bars in a row as pagina//id//1. Maybe I could use htaccess to adjust this url and remove duplicates.

  • Wallace, there are many cases where a URL parameter may come empty, a friendly url format pagination, for example. I keep several systems that do this and not only for paging. Example, for sending flags in segmented forms. Therefore, if you delete the double bars, the order of the parameters, in the case of friendly url, would conflict. The most important thing is to maintain the integrity of the parameters. If it will come empty, or with wrong number or letter, this is the model’s responsibility (mvc).

Show 1 more comment

2

No need to use regular expression, use array_diff(), I think it’s the shortest way to do:

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

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

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

  • Very good! Someone remembered the strtok!

  • @Wallacemaxters, for this case does not seem very practical but it is an option.

1

Get a basic treatment before using the 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 value $str = '/a//c/'; that would result in

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

In this case, the business model should be evaluated, whether or not to allow empty values.

0

You can use the array_diff():

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

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

print_r($saida);
  • 2

    I think that answer is already given here http://answall.com/a/81902/4995

Browser other questions tagged

You are not signed in. Login or sign up in order to post.