在理想情况下应该很容易完成的事情上几乎没有困难。
我想做的是用 &
替换最后一个单词之前的 ', '
。
所以基本上如果 $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);
}
请不要评判我,因为这只是尝试创建我在上面尝试描述的内容。
请帮忙
最佳答案
这是我对此的看法,使用 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;
关于php - 用&替换字符串中最后一个单词之前的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17896592/