簡體   English   中英

php替換特定字符的最后一個字符

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM