如何使用word_limiter获取第4和第7个单词

问题描述 投票:-3回答:2

喜;我想用word_limieter作为我的字符串

$string="this is a story of a man who was live in LA";
echo word_limiter($string, 4);

它在屏幕上打印:这是一个故事

但我希望得到第4和第7个单词之间(男人的故事)

我该怎么做 ?

php codeigniter
2个回答
2
投票

你不能用word_limiter()做,但你可以用array_slice()。注意起始字是它在数组中的位置:

$string="this is a story of a man who was live in LA";
$wordArr = explode(' ', $string);
$new = array_slice($wordArr, 3, 4); // starting word and length
$sentence = implode(' ', $new);
echo $sentence;

您可以在传递字符串和数组位置的地方编写一个函数:

function new_word_limiter($string, $start, $end) {
    $wordArr = explode(' ', $string);
    $new = array_slice($wordArr, $start, $end);
    $sentence = implode(' ', $new);
    return $sentence;
}

然后像这样称呼它:

new_word_limiter($string, 3, 4); // either echo or assign to variable

0
投票

试试这个:) substr(string,start,length)

echo substr("this is a story of a man who was live in LA", 10,14);

为了您的目的,您可以使用// substr($ string,5,15)

© www.soinside.com 2019 - 2024. All rights reserved.