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

标签 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); 
}

请不要评判我,因为这只是尝试创建我在上面尝试描述的内容。

请帮忙

最佳答案

这是我对此的看法,使用 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;

关于php - 用&替换字符串中最后一个单词之前的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17896592/

相关文章:

php - 如何在 PHP 中重新格式化日期?

PHP 包含不起作用

php - Laravel - 如何通过 hasMany 中的相关属性进行排序

php - Yii 2 : Can I access a variable in a view that's rendered by another view?

php - Youtube API 有什么问题(无效请求)?

php - Smarty - 变量加法

php - 将日期范围拆分为相应的周

php - 在mysql数据库中将文本保存为pre

php - 在安全方面,汇比源更重要吗?

php - 什么是 MediaWiki 中 AuthPlugin 上下文中的 "domain"?