Search code examples
phpstringduplicatesundorevert

PHP How to "unduplicate" a string after duplicating each character in the string (reverting the string)


Hi I need help with "unduplicating" a string (AKA reverting changes made to the string). I have a function in my PHP code which duplicates every character in the string ("Hello" becomes "HHeelllloo" etc). Now I want to revert that and I dont know how (AKA I want to turn my "HHeelllloo" into "Hello").

Here is the code:

<?php
            error_reporting(-1); // Report all type of errors
            ini_set('display_errors', 1); // Display all errors 
            ini_set('output_buffering', 0); // Do not buffer outputs, write directly
            ?>

            <!DOCTYPE html>
            <html>
            <head>
            <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
            <title>Untitled 1</title>
            </head>
            <body>
            <?php


            if(isset($_POST["dupe"]) && !empty($_POST["input"])){
                $input = $_POST["input"];
                $newstring = "";

                for($i = 0; $i < strlen($input); $i++){
                    $newstring .= str_repeat(substr($input, $i,1), 2);
                }

                echo $newstring;
            }

            if(isset($_POST["undupe"]) && !empty($_POST["input"])){

            }
            ?>

            <form method="post">
                <input type="text" name="input" placeholder="Input"></input><br><br>

                <button type="submit" name="dupe">Dupe</button>
                <button type="submit" name="undupe">Undupe</button>
            </form>

            </body>
            </html>

Now I dont know what to do when I press the "undupe" button. (Btw sorry if i made any mistakes in this post. Im new to stackoverflow.).


Solution

  • Since the string ordering isn't changed, just run over the string and skip ever second char:

    $undupe = '';
    for($i = 0; $i < strlen($duped); $i += 2) {
        $undupe .= $duped[$i]
    }
    

    e.g.

    HHeelllloo
    0123456789
    ^ ^ ^ ^ ^
    H e l l o
    ---------
    Hello