简体   繁体   中英

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 . Is it possible to replace the last comma so the message would be 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 :

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.

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM