July 27, 2013

Replacing comma with & before the last word in string

AlexB’s Question:

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

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>';

Here is another way:

$str = "A, B, C, D, E";
$pos = strrpos($str, ","); //Calculate the last position of the ","

if($pos) $str = substr_replace ( $str , " & " , $pos , 1); //Replace it with "&"
// ^ This will check if the word is only of one word.

For those who like to copy function, here is one 🙂

function replace_last($haystack, $needle, $with) {
    $pos = strrpos($haystack, $needle);
    return $pos !== false ? substr_replace($haystack, $with, $pos, strlen($needle)) : $haystack;
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!