【问题标题】:Stop explode after certain index [duplicate]在某个索引后停止爆炸[重复]
【发布时间】:2012-10-17 14:03:06
【问题描述】:

如何在某个索引后停止爆炸功能。 例如

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

如果只想使用前 10 个元素怎么办 ($result[10]) 填充 10 个元素后如何停止爆炸功能。

一种方法是首先将字符串修剪到前 10 个空格 (" ")

有没有其他方法,我不想在任何地方存储限制后的剩余元素(如使用正限制参数所做的那样)?

【问题讨论】:

    标签: php arrays explode


    【解决方案1】:

    函数的第三个参数是什么?

    数组爆炸(字符串 $delimiter , string $string [, int $limit ] )

    查看$limit 参数。

    手册:http://php.net/manual/en/function.explode.php

    手册中的一个例子:

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

    上面的例子会输出:

    数组 ( [0] => 一 [1] => 二|三|四) 数组 ( [0] => 一 [1] => 两个 [2] => 三)

    在你的情况下:

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

    根据php手册,当你使用limit参数时:

    如果 limit 设置为正,则返回的数组将包含一个 最大限制元素,最后一个元素包含其余元素 字符串。

    因此,您需要去掉数组中的最后一个元素。 您可以使用array_pop (http://php.net/manual/en/function.array-pop.php) 轻松完成。

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

    【讨论】:

    • 谢谢...有没有办法在正限制中丢弃下一个元素(在 limit 之后)?
    • 没听懂,能举个例子吗?
    • 就像在你的正限制示例中一样 [1] => two|three|four 我不想将这个元素 (Array[1]) 存储在任何地方,这应该被丢弃我只想要 Array ( [0] => one ) 而不是 Array ( [0] => one [1] => two|three|four )
    • 哦,好的,马上写一个解决方案
    • 问题是我的字符串很重,占用大量空间,这就是为什么由于内存问题我需要丢弃最后一个元素
    【解决方案2】:

    你可以read the documentation for explode:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 1970-01-01
      • 2023-01-30
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多