在理想情况下应该是一件简单的事情上没有什么麻烦。
我想做的是用&
替换最后一个单词之前的', '
。
所以基本上,如果CCD_ 3中的单词存在,就需要它作为&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;
我认为这是最好的方法:
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>';
基于正则表达式的解决方案:
$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
这里有另一种方法:
$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;
}