如何在某个索引后停止 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);