PHP 如何在复制字符串中的每个字符后“取消重复”字符串(还原字符串)


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

嗨,我需要有关"取消重复"字符串的帮助(AKA 还原对字符串所做的更改)。我的PHP代码中有一个函数,可以复制字符串中的每个字符("Hello"变成"HHeelllloo"等)。现在我想恢复它,我不知道如何(又名我想把我的"HHeelllloo"变成"你好")。

这是代码:

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

现在我不知道当我按下"unupe"按钮时该怎么办。(顺便说一句,如果我在这篇文章中犯了任何错误,我很抱歉。

由于字符串顺序没有更改,只需运行字符串并跳过第二个字符:

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

例如

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

您还可以在两个字符之间使用 preg_replace 和重置。替换为空字符串。

$str = preg_replace('/.'K./', "", $str);

这将去除所有其他字符。在 eval.in 上查看演示或在 regex101 上查看正则表达式演示


请注意,此正则表达式不会验证每个奇数字符是否匹配偶数。请与^(?:(.)'1)+$核实

这应该使您的代码正常工作:

$newstring = "";
for($i=0, $size=strlen($input); $i < $size; $i+=2){
    $newstring .= $input[$i];
}

另外,以防万一,请务必过滤/消毒 _POST 美元。