正在从取消数组末尾删除字符


Deleting character from the end of un array

我使用此代码显示字符串的第一个字母,其中$atit是该字符串的数组,结果必须类似于"R.&B.&T"。

有可能去掉最后一个"&"吗?我试图在echo行中使用rtrim,但它删除了所有的"&",而我只需要删除最后一个。

foreach ($atit as $ati) {
   $pieces = explode(' ', $ati);
   $otw = preg_replace('/'W'w+'s*('W*)$/', '$1', $pieces);  
   $acronym = "";
   foreach ($otw as $w) {
      $acronym .= $w[0].'. ';
   }
   $bla = $acronym.' & ';
   echo $bla;
} 

我认为foreach有问题,但我想不通。有什么建议吗?

更新:

数组中的每个条目都由几个单词组成,因此上面的代码被设计为显示除每个条目中最后一个单词外的所有单词的第一个字母。

示例:

$atit = ["Right now", "Behind you", "This is the time"];

因此,上面的代码将首先删除每个数组条目中的最后一个单词,然后获取并显示其中其余单词的第一个字母,类似于(R.&B.&T.I.T)。但问题是它在末尾添加了一个额外的"&"(R.&B.&T.I.T&)。

如果您的意思是形成一个由字符串数组中每个字符串的第一个字符组成的"首字母缩略词",这里是使用array_maparray_sliceimplodeexplodeucfirst函数的复杂解决方案:

$atit = ["Right now", "Behind you", "This is the time"];
$acronym = implode(" & ", array_map(function($v) {
    $words = explode(" ", $v);
    if (count($words) > 2) {
        return implode(".", array_map(function($w) {
                    return ucfirst($w[0]);
                }, array_slice($words, 0, -1)));
    }
    return $words[0][0] . ".";  // for simple strings (less/equal two words)
}, $atit));
echo $acronym;  // "R. & B. & T.I.T"

当用这样的分隔符连接多个元素时,我更喜欢每次都检查结果变量。如果不是空的,我会在连接分隔符前面加上。如果是空的,我不会。这样,就不会在末尾出现不需要的分隔符。

(或者只创建一个元素数组并使用PHP内爆()函数)

例如:

$array = array("a", "b", "c", "d");
$result = "";
foreach ($array as $a)
{
   if ($result != "") { $result .= " & "; }
   $result .= $a;
}
// $result = "a & b & c & d"

我不明白为什么需要regex,为什么在每次循环迭代中都要打印单独的字符串片段。

我可以建议这个解决方案:

$atit = ["Right now", "Behind you", "This is the time"];
$partList = array();
foreach ($atit as $ati) {
    $pieces = explode(' ', $ati);
    $numberOfPieces = sizeof($pieces);
    if ($numberOfPieces > 1) {
        $pieces = array_slice($pieces, 0, $numberOfPieces-1);
    }
    $acronym = "";
    foreach ($pieces as $w) {
        $acronym .= strtoupper($w[0]).'. ';
    }
    $partList[] = $acronym;
}
$bla = implode('& ', $partList);
echo $bla;