Replace first character with last character of mul

2019-08-03 07:31发布

问题:

I have this code

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

I need the output as Doog Reathew

回答1:

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


回答2:

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));

}