I use this code to display first letters from a string where $atit
is an array of that string and results must be something like "R. & B. & T.". But this code displays results like "R. & B. & T. &".
Is it possible to get rid of the last "&"? I tried to use rtrim
in echo
line but it deleted all "&" while I need to delete only the last one.
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;
}
I think it's a problem with foreach
but I couldn't figure it out. Any suggestions please?
Update:
Each entry in the array is comprised of several words so the code above is designed to display first letters of all words except for the last one in each entry.
Example:
$atit = ["Right now", "Behind you", "This is the time"];
So the code above will first delete the last word in each array entry and then get and display the first letters of the rest words in it, something like this (R. & B. & T. I. T). but the problem is that it adds an additional "&" to the end (R. & B. & T. I. T &).
If you meant formation of an "acronym" comprising of first character of each string from the array of strings - here is complex solution using array_map
, array_slice
, implode
, explode
and ucfirst
functions:
$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"