简体   繁体   English

用多个字符串PHP的最后一个字符替换第一个字符

[英]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 我需要输出作为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) { 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));

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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