【问题标题】:PHP How to "unduplicate" a string after duplicating each character in the string (reverting the string)PHP如何在复制字符串中的每个字符后“取消复制”字符串(恢复字符串)
【发布时间】:2016-06-05 13:49:11
【问题描述】:

您好,我需要有关“取消重复”字符串的帮助(AKA 恢复对字符串所做的更改)。我的 PHP 代码中有一个函数可以复制字符串中的每个字符(“Hello”变为“HHeelllloo”等)。现在我想恢复它,但我不知道如何(也就是我想把我的“HHeelllloo”变成“Hello”)。

代码如下:

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

现在我不知道当我按下“undupe”按钮时该做什么。 (顺便说一句,如果我在这篇文章中犯了任何错误,我很抱歉。我是 stackoverflow 的新手。)。

【问题讨论】:

  • 如果有人在字符串被复制之前点击了“Undupe”,应该是什么行为?

标签: php string duplicates undo revert


【解决方案1】:

由于字符串顺序没有改变,只需遍历字符串并跳过第二个字符:

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

例如

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

【讨论】:

  • 哦!谢谢!我不知道您可以通过使用数组索引从字符串中获取单个字符。 ($duped[$i])。
【解决方案2】:

您还可以在两个字符之间使用preg_replacereset。替换为空字符串。

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

这将删除所有其他字符。 See demo at eval.inregex demo at regex101


注意,这个正则表达式不会验证每个奇数字符是否匹配偶数。检查^(?:(.)\1)+$

【讨论】:

    【解决方案3】:

    这应该使您的代码工作:

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

    另外,以防万一,make sure to filter/sanitize $_POST

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 2020-06-29
      相关资源
      最近更新 更多