在 PHP 中生成批量唯一字符串

Generate Bulk Unique Strings in PHP

我有一个 working 脚本,旨在在检查数据库后生成和输出大量唯一字符串 and/or文本文档(这还不包括在内 - 但我不请求有关检查数据库的帮助)并检查同一请求中已经生成的字符串。

我确实用一个函数尝试过这个,但我不知道如何在一个函数中进行这么多检查,因此这段代码对于我想要实现的目标来说感觉很长。

我希望社区能够以最合适的 and/or 合规方式帮助我以最少的请求或代码在某些方面得到保护和简化来完成以下任务方式?

该脚本基本上采用 'range' 或限制输入,并将该数量的随机字符串(例如:aa0aa0)生成为 table。我正在使用 substr()str_shuffle()str_repeat(),但我已经看到其他用途,例如 mt_rand(),但由于害怕破坏它而没有尝试更改此代码。

我发布这个是因为除了一些非常复杂的函数外,没有简单的方法来做'reverse regex',但我发现如果代码中已经规定了字符串格式,这是一种简单的方法。

如有任何想法and/or,我们将不胜感激。

<?php

/**
 * This just stops the errors that a unset/zero range throws 
 * back with populateRandomString() and exportRandomString().
 */
if( isset( $_REQUEST['range'] ) ) {
    
    $range = $_REQUEST['range'];
    
    if( $range == 0 ) {
        
        unset( $range );
    }
    
}
if( !isset( $_REQUEST['range'] ) ) {
    
    $range = null;
    
} ?>

<h3>Generate Strings</h3>

<form><input type="text" name="range" value="<?php if( isset( $range ) ) { echo $range; } else { echo ''; } ?>"><input type="submit" action="" ></form>

<?php
function generateRandomString() {
    
    /**
     * This is just a hack for when existing values from this 
     * function are saved, either in a text document or database.
     */
    $db_existing = ''; // Will eventually call the database or text file.
    $existing_array = explode( ',', $db_existing );
    
    /**
     * Combinations of letters and numbers that will be generated by 
     * generateRandomString().
     */
    $letter = 'abcdefghijklmnopqrstuvwxyz';
    $number = '0123456789';

    start:
    
    for ($i = 0; $i < 1; $i++) {

        /**
         * I could not find any research that supported regex developing certain
         * strings (simply), so this is the only way that I could do it. I'm
         * looking for the most efficient way to generate these strings
         */
        $generateString  = substr ( str_shuffle ( str_repeat ( $letter, 2 ) ), 1 , 2 );
        $generateString .= substr ( str_shuffle ( str_repeat ( $number, 1 ) ), 1 , 1 );
        $generateString .= substr ( str_shuffle ( str_repeat ( $letter, 2 ) ), 1 , 2 );
        $generateString .= substr ( str_shuffle ( str_repeat ( $number, 1 ) ), 1 , 1 );
        // output example: aa0aa0
    }
    
    /**
     * If the random generated string has already been generated and is part
     * of the existing strings (database or text file, it will ignore it and
     * cycle again.
     */
    if ( in_array ( $generateString, $existing_array ) ) {
        
        goto start;
        
    } else {
        
        return $generateString;
        
    }

}
if( isset( $range ) ) {
    
    function populateRandomString() {
        
        global $range;
        
        /**
         * If the string has already been generated in this request, ignore it
         * and generate it again until the range (limit) has been met.
         */
        
        start :
        for( $i = 0; $i < $range; $i++ ) {
            
            $populateRandomString[] = generateRandomString();
            
        }
        
        if( count( array_unique( $populateRandomString ) ) < $range ) {
                
            unset( $populateRandomString);
            goto start;
        
        } else {

            return $populateRandomString;
        
        }

    }

    function exportRandomString() {

        global $range;
        
        /**
         * Display the generated strings in a table as described in the html
         * output below.
         */
        
        for ( $e = 0; $e < $range; $e++ ) {

            $id[] = populateRandomString();

        }
        
    }
    $id = populateRandomString(); ?>
    
<table id="myTable" width="50%">
  <thead>
   <tr>
    <th scope="col">Title 1</th>
    <th scope="col">Title 2</th>
    <th scope="col">ID</th>
    </tr>
  </thead>

  <tbody>
    
    <?php foreach ( $id as $i ) { ?>
  <tr>  
    <td>https://www.example.com/<?php echo $i; ?></td>
    <td>https://www.example.com/<?php echo $i; ?></td>
    <td><?php echo strtoupper($i); ?></td>
  </tr>
    <?php } ?>
    
  </tbody>
</table>
<style>
  #myTable{
     font-family: 'helvetica neue',helvetica,arial,'lucida grande',sans-serif;
     border-collapse: collapse;
  }
  #myTable td{
     border: solid 1px #C9C9C9;
     padding: 10px;
     font-size: 12px;
     text-align: left;
  }
  #myTable th {
      text-align: left;
  }
  #myTable tr{
     background-color: #EBEBEB;
     color: #000000;
  }
  #myTable tr:hover{
     background-color: #FFFFFF;
     color: #000000;
  }

</style>    
    <?php
}

你真的应该详细说明你的问题并清理你的代码。看起来很乱,用起来更乱。尽管如此,我还是试了一下。

我使用 docker-compose 一个容器 运行 apache,另一个 MySQL。我添加了准备好的语句支持,这对于这个应用程序来说似乎有点矫枉过正,但无论如何都是很好的做法。但是,您需要在 PHP 代码中更新数据库信息。

这是我的尝试:

<?php

    // Simplified below code. 
    $range = null;
    if( isset( $_REQUEST['range'] ) && $_REQUEST['range'] != 0 ) {
            $range = intval($_REQUEST['range']);
    }

    
    //                          db host        user    pass    db schema
    if ($conn = mysqli_connect("overflow_db", "root", "test", "testone")) {} else { // Here you will have to update the credentials for your database.
        die("could not connect to database. :(");
    }
    


    function getAllStringsDb() {
        // Grab all previously generated strings from db and load into $existing_array (array) on global scope.

        global $existing_array; // Declare the existing strings on a global scope.
        $existing_array = array();

        $conn = $GLOBALS['conn'];
        
        $sql = "SELECT * FROM stored_strings";
        $stmt = $conn->prepare($sql);

        $stmt->execute();

        $result = $stmt->get_result();
        if ($result->num_rows === 0) {
            return null;
        } else {
            while ($row = $result->fetch_assoc()) {
                $existing_array[] = $row['string_value'];
            }
        }
        $stmt->close();

        return $existing_array;

    }

    function saveNewStringsToDb($return_array) {

        $conn = $GLOBALS['conn'];
        
        $sql = "INSERT INTO stored_strings (string_value) VALUES (?)";
        
        foreach ($return_array as $value) {
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("s", $value);

            if (!$stmt->execute()) {
                die("DB save failed. :( ");
            }

            $stmt->close();
        }

    }


    function getString($existing_array) {
        $string_length = 6;

        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';

        start:
        $generateString = '';
        for ($n = 0; $n < $string_length; $n++) {

            $generateString .= $characters[rand(0, strlen($characters) - 1)];
        }

        if ( in_array ( $generateString, $existing_array ) ) {
            goto start;
        } else {
            // Add new string to db.
            $existing_array[] = $generateString;
            return $generateString;
        }
    }

    function generateRandomStrings($range) {

        // Generate all the new strings into the array $return_array.
        for ($i = 0; $i < $range; $i++) {
            $return_array[] = getString([]);
        }

        // Upload all the newly generated strings to the database. 
        saveNewStringsToDb($return_array);

        return $return_array; // Return array.

    }

?>



<h3>Generate Strings</h3>

<form>
    <input type="number" name="range" value="<?php if (isset($range)) { echo $range; } else { echo ''; } ?>" />
    <input type="submit" action="" />
</form>




<?php
    if( isset( $range ) ) {

        getAllStringsDb(); // Load in all previously generated strings into the array $existing_array from the database.
        
        $ids = generateRandomStrings($range);
?>

<table id="myTable" width="50%">
    <thead>
        <tr>
            <th scope="col">Title 1</th>
            <th scope="col">Title 2</th>
            <th scope="col">ID</th>
        </tr>
    </thead>

    <tbody>

        <?php foreach ( $ids as $i ) { ?>
            <tr>
                <td>https://www.example.com/<?php echo $i; ?></td>
                <td>https://www.example.com/<?php echo $i; ?></td>
                <td><?php echo strtoupper($i); ?></td>
            </tr>
        <?php } ?>

    </tbody>
</table>

<style>
    #myTable {
        font-family: 'helvetica neue', helvetica, arial, 'lucida grande', sans-serif;
        border-collapse: collapse;
    }

    #myTable td {
        border: solid 1px #C9C9C9;
        padding: 10px;
        font-size: 12px;
        text-align: left;
    }

    #myTable th {
        text-align: left;
    }

    #myTable tr {
        background-color: #EBEBEB;
        color: #000000;
    }

    #myTable tr:hover {
        background-color: #FFFFFF;
        color: #000000;
    }
</style>
<?php
    }
?>

下面是我用于上述代码的基本数据库结构:

DROP TABLE IF EXISTS `stored_strings`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `stored_strings` (
  `string_id` int NOT NULL AUTO_INCREMENT,
  `string_value` varchar(255) NOT NULL,
  PRIMARY KEY (`string_id`)
) ENGINE=InnoDB AUTO_INCREMENT=416 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

我会敦促您从头开始重写您的代码,以使其变得更好。另外,请对我上面提供的代码持保留态度,因为它是基于您现有代码的简单草稿。 :)