从两个不同的字符串动态打印替代字符串字符

时间:2017-11-18 12:34:34

标签: javascript php arrays wordpress codeigniter

我试图动态地从两个不同的字符串中打印替代字符。我做了下面的代码,但它给了我" TrAaUuSt"这个输出。但我想" TrAaUuStIF"。我怎么解决这个问题?有人可以帮帮我吗?先感谢您。我是PHP的新手。如果您有更好的解决方案,请建议我。

<?php

/*$str1 = "TAUSIF";
$str2 = "raut";
Output = TrAaUuSt*/


if(isset($_POST['submit']))
{   
    $str1 = $_POST['str1'];
    $str2 = $_POST['str2'];

    $strlen1 = strlen($str1);
    $strlen2 = strlen($str2);


    if($strlen1 > $strlen2)
    { 
        for($i = 0; $i<$strlen2; $i++){         
            $new[] = $str1[$i];
            $new[] = $str2[$i];       
        }

    }
    else
    {
        for($i = 0; $i<$strlen1; $i++){ 
            $new[] = $str1[$i]; 
            $new[] = $str2[$i]; 
        }

    }

    foreach($new as $str){
        echo $str;
    }
}
?>




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Print alternative character.</title>
</head>
<body>

   <form action="" method="post">
       <input type="text" name="str1" ><br><br>
       <input type="text" name="str2" ><br><br>
       <input type="submit" name="submit" value="Submit" >
   </form>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

if(isset($_POST['submit']))
{  
    //$str1 = "TAUSIF";
    //$str2 = "raut";

    $str1 = $_POST['str1'];
    $str2 = $_POST['str2'];

    // SPLIT STRINGS TO ARRAY
    $a1 = str_split($str1);
    $a2 = str_split($str2);

    $out = ''; // THE OUTPUT STRING

    // CHECK WHICH STRING IS LONGEST
    $count = (count($a1) > count($a2)) ? count($a1) : count($a2);

    // LOOP BASED ON THE NUMBER OF CHARACTERS IN LONGEST STRING
    for ($x = 0; $x <= $count; $x++) {
        $out .= (isset($a1[$x])) ? $a1[$x] : '';
        $out .= (isset($a2[$x])) ? $a2[$x] : '';    
    }

    echo $out;  // TrAaUuStIF
}

注意: 如果您需要Unicode支持,那么您应该考虑按照此处最高投票评论中的说明制作您自己的str_split函数:http://php.net/str_split

答案 1 :(得分:0)

<?php

/*$str1 = "TAUSIF";
$str2 = "raut";
Output = TrAaUuSt*/


if(isset($_POST['submit']))
 {   
$str1 = $_POST['str1'];
$str2 = $_POST['str2'];

$strlen1 = strlen($str1);
$strlen2 = strlen($str2);


if($strlen1 > $strlen2)
   { 
    for($i = 0; $i<$strlen2+$strlen1; $i++){         
            $new[] = $str1[$i];
            $new[] = $str2[$i];       
    }


   }else
    {
    for($i = 0; $i<$strlen1+$strlen2; $i++){ 
        $new[] = $str1[$i]; 
        $new[] = $str2[$i]; 
    }

}

foreach($new as $str){
    echo $str;
}
}
?>




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Print alternative character.</title>
</head>
<body>

   <form action="" method="post">
       <input type="text" name="str1" ><br><br>
       <input type="text" name="str2" ><br><br>
       <input type="submit" name="submit" value="Submit" >
   </form>

</body>
</html>