Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing comma with & before the last word in string

Tags:

php

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

like image 794
AlexB Avatar asked Jul 27 '13 10:07

AlexB


2 Answers

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) . " &amp; " . $last;
like image 129
Madara's Ghost Avatar answered Oct 04 '22 16:10

Madara's Ghost


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, ', ', ' &amp; ');
echo $replaced.'<br>';
like image 29
core1024 Avatar answered Oct 04 '22 14:10

core1024