【问题标题】:PHP : Add word from array to string after every 5 wordsPHP:每5个单词后将单词从数组添加到字符串
【发布时间】:2023-03-05 00:18:01
【问题描述】:

我有一个字符串,我想在每 5 个单词之后输入一个单词。这个词来自数组。

French History Maths Physics Spanish Chemistry Biology English DT Maths History DT Spanish English French RS

我想从数组中获取 2 个单词,然后在 5 个单词之后将其插入到上面的字符串中。

$words = arrray(a, able, about, above, abst, accordance, according, accordingly, across, act, actually, added, adj);

喜欢这个输出:

French History Maths Physics Spanish a able about above abst Chemistry Biology English DT Maths according according accordingly across act Spanish English French RS.

【问题讨论】:

  • 您是否对此进行过任何尝试,请在问题中添加任何代码(非工作代码也可以)。
  • 我已经做了任何尝试。我不知道如何开始。感谢您回复我的问题
  • 但在您的示例中,您在每 5 个单词后添加 5 个来自 array 的单词,而不是 2 个或者我误解了?
  • php explode: split string into words by using space a delimiter 周围有资源,这至少是一个开始。
  • @Joseph 是的,但这只是我想展示的概念。抱歉插入 5 个字。

标签: php arrays


【解决方案1】:
$string = 'French History Maths Physics Spanish Chemistry Biology English DT Maths History DT Spanish English French RS';
$words  = array('a', 'able', 'about', 'above', 'abst', 'accordance', 'according', 'accordingly', 'across', 'act', 'actually', 'added', 'adj');
$result = [];

$xpld = explode(' ',$string);
if(!empty($xpld))
{
  $count = 0;
  for ($i=0; $i < sizeof($xpld) ; $i++) 
  {
    if ($i % 5 == 0 && $i > 0) 
    {
      for ($j=$count; $j < $count + 5 ; $j++) 
      {
        $result[] = @$words[$j];
      }
      $count = $j;
    }
    $result[] = $xpld[$i];
  }
}
$result = implode(' ',$result);
echo $result;

上面的代码和你的例子一样,但我不知道它是否有效,请注意我使用suppress @ 来避免你的数组单词超出索引

【讨论】:

  • 非常感谢,这就是我正在寻找的答案。
猜你喜欢
  • 1970-01-01
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 2013-11-30
相关资源
最近更新 更多