[英]php replace last character of specific character
I have an array and I want to generate a message out of them. 我有一个数组,我想从它们生成一个消息。 If I use
join(', ', $response)
, I get file1.jpg, file2.jpg, file3.jpg
. 如果我使用
join(', ', $response)
,我会得到file1.jpg, file2.jpg, file3.jpg
。 Is it possible to replace the last comma so the message would be file1.jpg, file2.jpg AND file3.jpg
? 是否可以替换最后一个逗号,因此消息将是
file1.jpg, file2.jpg AND file3.jpg
?
This should work; 这应该工作;
<?php
$response=['file1.jpg','file2.jpg','file3.jpg'];
$response=array_reverse($response);
$arr=$response[1].' AND ' .$response[0];
for ($i=2; $i < count($response); $i++) {
$new[]=$response[$i];
}
array_push($new, $arr);
echo join(", ",$new);
You can use array_slice
to get all the elements in the array but the last one and make a special case for it : 您可以使用
array_slice
来获取数组中的所有元素,但是最后一个元素并为它创建一个特例:
function formatList($response)
{
if(count($response) == 0)
return '' ;
if(count($response) == 1)
return $response[0] ;
else
return join(', ', array_slice($response, 0, count($response)-1)) . ' AND ' . end($response);
}
substr_replace
replace a portion of a string by position and length, strrpos
find position of the last comma. substr_replace
按位置和长度替换字符串的一部分, strrpos
查找最后一个逗号的位置。
$response = ['file1.jpg', 'file2.jpg', 'file3.jpg'];
$out = join(', ', $response);
echo substr_replace($out, " AND", strrpos(($out), ','), 1);
https://www.php.net/manual/en/function.substr-replace.php https://www.php.net/manual/en/function.strrpos.php https://www.php.net/manual/en/function.substr-replace.php https://www.php.net/manual/en/function.strrpos.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.