【问题标题】:Replace first character with last character of multiple strings PHP用多个字符串的最后一个字符替换第一个字符PHP
【发布时间】:2014-05-13 03:16:27
【问题描述】:

我有这个代码

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

我需要输出为 Doog Reathew

【问题讨论】:

    标签: php string function replace


    【解决方案1】:

    使用下面的代码可以解决您的目的。已添加评论以供您理解。

    <?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
    

    【讨论】:

    • @DummyCode,我用过ucfirst() ;) 仔细查看代码。
    • reathew 怎么样?那可能吗?我只想要第一个字母和最后一个字母,但 mod 编辑了它 lomo。
    • @user3487504 然后删除ucfirst。见,php.net/manual/en/function.ucfirst.php
    【解决方案2】:

    只要写下面的函数,就可以了

    函数替换($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));
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多