理想情况下应该完成一件简单的事情。
我要做的是在', '
的最后一个单词之前替换&
。
所以基本上如果$ddd
中的单词存在而不是需要它作为& DDD,如果$ddd
为空,则为& CCC
从理论上讲,我需要采取的措施如下:
当所有4个单词都不为空时,“AAA,BBB,CCC和DDD” “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);
}
请不要评判我,因为这只是尝试创造我上面试图描述的东西。
请帮忙
答案 0 :(得分: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) . " & " . $last;
答案 1 :(得分:1)
基于正则表达式的解决方案:
$str = "A, B, C, D, E";
echo preg_replace('~,(?=[^,]+$)~', '&', $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
答案 2 :(得分: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, ', ', ' & ');
echo $replaced.'<br>';
答案 3 :(得分: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;
}