有人问如何把he_llo wo_rld 变成 HeLlo WoRld,估计应该是一道面试的基础题吧。

思路很多种,就看如何实现

思路一、先根据空格分隔,然后转大写,最后再拼接。代码如下

<?php
function change_string1($string="")
{
    $array=explode(" ",$string);
    foreach ($array as $key => $v)
    {
        $array[$key]=str_replace(" ","",ucwords(str_replace("_"," ",$v)));
    }
    $string=implode(" ",$array);
    return $string;
}

$string="he_llo wo_rld";
$string=change_string1($string);
var_dump($string);
?>

效果如图:

如何把he_llo wo_rld 变成 HeLlo WoRld

思路二、先将空格替换为两个空格,然后将下划线替换为一个空格,然后转大写,之后把两个空格替换为下划线,再把一个空格替换为空,再把下划线替换为一个空格,代码如下:

<?php
function change_string2($string="")
{
    $string=str_replace(" ","  ",$string);
    $string=str_replace("_"," ",$string);
    $string=ucwords($string);
    $string=str_replace("  ","_",$string);
    $string=str_replace(" ","",$string);
    $string=str_replace("_"," ",$string);
    return $string;
}

$string="he_llo wo_rld";
$string=change_string1($string);
var_dump($string);
?>

效果如图:

如何把he_llo wo_rld 变成 HeLlo WoRld

思路三、采用字符串循环解决,代码如下:

<?php
function change_string3($string="")
{
    $length=strlen($string);
    for ($i=0; $i <$length ; $i++)
    {
        if($string{$i}===" "||$string{$i}==="_")
        {
            $string{$i+1}=strtoupper($string{$i+1});
        } 
    }
    $string=ucfirst(str_replace("_","", $string));
    return $string;
}

$string="he_llo wo_rld";
$string=change_string3($string);
var_dump($string);
?>

效果如图:

如何把he_llo wo_rld 变成 HeLlo WoRld

 

相关文章:

  • 2022-12-23
  • 2021-04-02
  • 2021-08-28
  • 2022-02-08
  • 2021-11-14
  • 2021-07-25
  • 2021-06-30
  • 2021-05-24
猜你喜欢
  • 2021-09-06
  • 2022-02-17
  • 2021-07-27
  • 2022-12-23
  • 2021-11-20
  • 2022-12-23
  • 2021-07-29
相关资源
相似解决方案