Stop explode after certain index

不想你离开。 提交于 2019-11-28 08:52:31

问题


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

    <?php
        $test="The novel Prognosis Negative by Art Vandelay expresses protest against many different things. The story covers a great deal of time and takes the reader through many different places and events, as the author uses several different techniques to really make the reader think. By using a certain type of narrative structure, Vandelay is able to grab the reader’s attention and make the piece much more effective and meaningful, showing how everything happened";

    $result=explode(" ",$test);
    print_r($result);
?>

What if want to use only first 10 elements ($result[10]) How can I stop explode function once 10 elements are filled.

One way is to first trim the string upto first 10 spaces (" ")

Is there any other way, I don't want to store the remaining elements after limit anywhere (as done using positive limit parameter)?


回答1:


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);



回答2:


You could read the documentation for explode:

$result = explode(" ", $test, 10);


来源:https://stackoverflow.com/questions/12936120/stop-explode-after-certain-index

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!