Stop explode after certain index

前端 未结 2 550
醉酒成梦
醉酒成梦 2020-12-21 06:44

How can I stop explode function after certain index. For example

    

        
相关标签:
2条回答
  • 2020-12-21 07:14

    You could read the documentation for explode:

    $result = explode(" ", $test, 10);
    
    0 讨论(0)
  • 2020-12-21 07:17

    What's about that third parameter of the function?

    array explode ( string $delimiter , string $string [, int $limit ] )

    check out the $limit parameter.

    Manual: http://php.net/manual/en/function.explode.php

    An example from the manual:

    <?php
    $str = 'one|two|three|four';
    
    // positive limit
    print_r(explode('|', $str, 2));
    
    // negative limit (since PHP 5.1)
    print_r(explode('|', $str, -1));
    ?>
    

    The above example will output:

    Array ( [0] => one [1] => two|three|four ) Array ( [0] => one [1] => two [2] => three )

    In your case:

    print_r(explode(" " , $test , 10));
    

    According to the php manual , when you're using the limit parameter:

    If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

    Therefore , you need to get rid of the last element in the array. You can do it easily with array_pop (http://php.net/manual/en/function.array-pop.php).

    $result = explode(" " , $test , 10);
    array_pop($result);
    
    0 讨论(0)
提交回复
热议问题