在字符串中的最后一个单词之前用&替换逗号

Ale*_*exB 7 php

理想情况下应该完成什么应该是一件简单的事情.

我要做的是', '在最后一个单词之前替换&.

所以基本上如果$ddd存在的话比需要它作为&DDD而且如果$ddd是空的而不是& CCC

从理论上讲,我需要做的是以下内容:

"AAA,BBB,CCC和DDD"当所有4个单词都不为空时"AAA,BBB&CCC",当3不为空时,最后一个是"AAA&BBB",当2不为空且最后2个单词为空时"AAA "当只返回一个非空时.

这是我的剧本

    $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); 
}
Run Code Online (Sandbox Code Playgroud)

请不要评判我,因为这只是尝试创造我试图在上面描述的东西.

请帮忙

Mad*_*iha 6

以下是我对此的看法,使用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;
Run Code Online (Sandbox Code Playgroud)


cor*_*024 1

我认为这是最好的方法:

function replace_last($haystack, $needle, $with) {
    $pos = strrpos($haystack, $needle);
    if($pos !== FALSE)
    {
        $haystack = substr_replace($haystack, $with, $pos, strlen($needle));
    }
    return $haystack;
}
Run Code Online (Sandbox Code Playgroud)

现在你可以像这样使用它:

$string = "AAA, BBB, CCC, DDD, EEE";
$replaced = replace_last($string, ', ', ' &amp; ');
echo $replaced.'<br>';
Run Code Online (Sandbox Code Playgroud)