gpt4 book ai didi

php - 我想过滤一个字符串并使用 php 创建一个数组

转载 作者:搜寻专家 更新时间:2023-10-31 20:37:29 24 4
gpt4 key购买 nike

这是我的示例字符串(这个有五个单词;在实践中,可能会有更多):

$str = "I want to filter it";

我想要的输出:

$output[1] = array("I","want","to","filter","it");
$output[2] = array("I want","want to","to filter","filter it");
$output[3] = array("I want to","want to filter","to filter it");
$output[4] = array("I want to filter","want to filter it");
$output[5] = array("I want to filter it");

我正在尝试:

$text = trim($str);
$text_exp = explode(' ',$str);
$len = count($text_exp);
$output[$len][] = $text; // last element
$output[1] = $text_exp; // first element

这给了我第一个和最后一个数组。如何获取所有中间数组?

最佳答案

适用于任何长度单词的更通用的解决方案:

$output = array();

$terms = explode(' ',$str);
for ($i = 1; $i <= count($terms); $i++ )
{
$round_output = array();
for ($j = 0; $j <= count($terms) - $i; $j++)
{
$round_output[] = implode(" ", array_slice($terms, $j, $i));
}
$output[] = $round_output;
}

关于php - 我想过滤一个字符串并使用 php 创建一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31534082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com