7

理想情况下应该是一件容易完成的事情。

我想要做的是', '在最后一个词之前用&.

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

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

“AAA, BBB, CCC & DDD” 当所有 4 个单词不为空时 “AAA, BBB & CCC” 当 3 个不为空且最后一个为 “AAA & BBB” 当 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); 
}

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

请帮忙

4

4 回答 4

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;
于 2013-07-27T10:15:13.447 回答
1

基于正则表达式的解决方案:

$str = "A, B, C, D, E";

echo preg_replace('~,(?=[^,]+$)~', '&amp;', $str);

正则表达式解释:

, -- a comma
(?=[^,]+$) -- followed by one or more any characters but `,` and the end of the string

关于断言的文档((?= ... )我的回答中使用了积极的前瞻):http ://www.php.net/manual/en/regexp.reference.assertions.php

于 2013-07-27T10:21:26.350 回答
1

我认为这是最好的方法:

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

现在你可以这样使用它:

$string = "AAA, BBB, CCC, DDD, EEE";
$replaced = replace_last($string, ', ', ' &amp; ');
echo $replaced.'<br>';
于 2013-07-27T10:28:16.023 回答
0

这是另一种方式:

$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.

对于那些喜欢复制功能的人,这里有一个:)

function replace_last($haystack, $needle, $with) {
    $pos = strrpos($haystack, $needle);
    return $pos !== false ? substr_replace($haystack, $with, $pos, strlen($needle)) : $haystack;
}
于 2013-07-27T10:17:02.987 回答