简体   繁体   中英

Replace first character with last character of multiple strings PHP

I have this code

<?php
$str1 = 'Good'
$str2 = 'Weather'
echo $str1, $str2

I need the output as Doog Reathew

Using the below piece of code solves your purpose. Comments have been added for your understanding.

<?php
$str1 = 'Good';
$str2 = 'Weather';

function swaprev($str1)
{
$str1 = str_split($str1);  //<--- Split the string into separate chars

$lc=$str1[count($str1)-1]; # Grabbing last element
$fe=$str1[0];              # Grabbing first element
$str1[0]=$lc;$str1[count($str1)-1]=$fe;    # Do the interchanging
return $str1 = implode('',$str1);  # Recreate the string
}

echo ucfirst((strtolower(swaprev($str1))))." ".ucfirst((strtolower(swaprev($str2))));

OUTPUT :

Doog Reathew

just write below function ,it will work

function replace($string) {

$a = substr($string, 0, 1);
$b = substr($string, -1);
$string = $b . (substr($string, 1, strlen($string)));
$string = substr($string, 0, strlen($string) - 1);
$string = $string . $a;

return ucfirst(strtolower($string));

}

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