dongyan3853 2009-05-30 06:17
浏览 45
已采纳

使用PHP在数组中交替大写字母

I have an alphanumeric string like below,

$string_1 = "a4nas60dj71wiena15sdl1131kg12b"

and would like to change it to something like below,

$string_2 = "a4NaS60dJ71wIeNa15Sdl1131Kg12B"

How would I go about doing this? I have tried the below code, but it doesn't work.

$lenght = strlen($string_1);

for ( $i = 0; $i <= $length - 1; $i += 1) {

    if ( $i % 2) {

        $string_2[$i]=strtoupper($string_1[$i]);

    }

    else {

        $string_2[$i]=$string_1[$i];

    }

}

echo $string_2;

The above code prints out "Array" so something is definitely not working.

  • 写回答

3条回答 默认 最新

  • doumanju2533 2009-05-30 06:27
    关注

    By the way, you have a slight error in your capitalized string:

    $string_1: a4nas60dj71wiena15sdl1131kg12b
    $string_2: a4NaS60dJ71wIeNa15Sdl1131Kg12B
                                   ^ should be capital so out of sync for rest of string
    

    I'll give you two ways of doing it:

    <?php
    header('Content-Type: text/plain');
    
    $string_1 = "a4nas60dj71wiena15sdl1131kg12b";
    $string_2 = "a4NaS60dJ71wIeNa15Sdl1131Kg12B";
    
    $letter_count = 0;
    $result = '';
    for ($i=0; $i<strlen($string_1); $i++) {
        if (!preg_match('![a-zA-Z]!', $string_1[$i])) {
            $result .= $string_1[$i];
        } else if ($letter_count++ & 1) {
            $result .= strtoupper($string_1[$i]);
        } else {
            $result .= $string_1[$i];
        }
    }
    
    $result2 = preg_replace_callback('!([a-zA-Z]\d*)([a-zA-Z])!', 'convert_to_upper', $string_1);
    
    function convert_to_upper($matches) {
        return strtolower($matches[1]) . strtoupper($matches[2]);
    }
    
    echo "$string_1
    ";
    echo "$string_2
    ";
    echo "$result
    ";
    echo "$result2
    ";
    ?>
    

    Note: The above makes several assumptions:

    1. Characters other than numbers and letters can be in the string;
    2. You want to alternate case regardless of the original (eg "ASDF" becomes "aSdF");
    3. You're capitalizing every second letter, not every second lowercase letter.

    The above can be altered if these assumptions are incorrect.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据