php - 一定指数后停止 explode

标签 php arrays explode

<分区>

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

    <?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 个元素后如何停止 explode 功能。

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

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

最佳答案

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

array explode ( string $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));
?>

上面的例子会输出:

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

在你的情况下:

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

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

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.

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

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

关于php - 一定指数后停止 explode ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12936120/

相关文章:

javascript - 使用 json 的 java 脚本创建类似 Hashmap 的实现

java - 如何将对象添加到 2D 对象数组中的特定 x,y 位置

c++ - vector::erase 如何从其内部数组中删除所选元素

PHP:如何结合 foreach 和 explode

php - 在 php 中处理新行

php - 在 php 中分解一个字符串,不包括大括号内的 ', '

php - 使用命令 'php artisan serve' 运行 Laravel 有什么意义?

PHP 从 zip 文件目录中读取文本文件

php - MySQLi 预处理语句和 foreach 循环

php - 根据用户输入 php 更新数据库