[英]php replace last character of specific character
我有一个数组,我想从它们生成一个消息。 如果我使用join(', ', $response)
,我会得到file1.jpg, file2.jpg, file3.jpg
。 是否可以替换最后一个逗号,因此消息将是file1.jpg, file2.jpg AND file3.jpg
?
这应该工作;
<?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);
您可以使用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
按位置和长度替换字符串的一部分, 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.