Having little trouble with what should ideally be a simple thing to accomplish.
What I am trying to do is to replace ', '
before the last word with &
.
So basically if word in $ddd
exist than need it as & DDD and if $ddd
is empty than & CCC
Theoretically speaking, what i do need to acive is the following:
"AAA, BBB, CCC & DDD" when all 4 words are not empty "AAA, BBB & CCC" when 3 are not empty and last one is "AAA & BBB" when 2 are not empty and 2 last words are empty "AAA" when only one is returned non empty.
Here is my script
$aaa = "AAA";
$bbb = ", BBB";
$ccc = ", CCC";
$ddd = ", DDD";
$line_for = $aaa.$bbb.$ccc.$ddd;
$wordarray = explode(', ', $line_for);
if (count($wordarray) > 1 ) {
$wordarray[count($wordarray)-1] = '& '.($wordarray[count($wordarray)-1]);
$line_for = implode(', ', $wordarray);
}
Please do not judge me, since this is just an attempt to create something that I have tried to describe above.
Please help
Here's my take on this, using array_pop()
:
$str = "A, B, C, D, E";
$components = explode(", ", $str);
if (count($components) <= 1) { //If there's only one word, and no commas or whatever.
echo $str;
die(); //You don't have to *die* here, just stop the rest of the following from executing.
}
$last = array_pop($components); //This will remove the last element from the array, then put it in the $last variable.
echo implode(", ", $components) . " & " . $last;
I think this is the best way to do it:
function replace_last($haystack, $needle, $with) {
$pos = strrpos($haystack, $needle);
if($pos !== FALSE)
{
$haystack = substr_replace($haystack, $with, $pos, strlen($needle));
}
return $haystack;
}
and now you can use it like that:
$string = "AAA, BBB, CCC, DDD, EEE";
$replaced = replace_last($string, ', ', ' & ');
echo $replaced.'<br>';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With