PHP Ticket ID Generation - php

I am creating a ticket system for learning purposes, and I was wondering how would I create a simple unique ticket ID that would be similiar to this: gD8f-jxS
It would have 4 characters of random case in the first part
(letters and numbers are allowed, then it would have a dash, and again 3 random letters or numbers of any case.

public function generateCode(){
$unique = FALSE;
$length = 7;
$chrDb = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9');
while (!$unique){
$str = '';
for ($count = 0; $count < $length; $count++){
$chr = $chrDb[rand(0,count($chrDb)-1)];
if (rand(0,1) == 0){
$chr = strtolower($chr);
}
if (3 == $count){
$str .= '-';
}
$str .= $chr;
}
/* check if unique */
//$existingCode = UNIQUE CHECK GOES HERE
if (!$existingCode){
$unique = TRUE;
}
}
return $str;
}

Related

Random string rules

I have a function that generates a random 3-character alpha-numeric string. I need to modify it in such a way that the new string consisted of 2 alpha and 2 numeric characters. The combination of numbers and letters can be random.
function generate_random($length = 3) {
$characters = '123456789ABCDEFGHJKLMNPRSTUVWXYZ';
$rand_str = '';
for ($p = 0; $p < $length; $p++) {
$rand_str .= $characters[mt_rand(0, strlen($characters)-1)];
}
return $rand_str;
}
I need to modify it in such a way that the new string consisted of 2 alpha and 2 numeric characters. The combination of numbers and letters can be random. How do I do that?
I would personally do it this way:
function generate_random($countAlpha = 2, $countNumeric = 2, $randomize = true) {
$alpha = 'ABCDEFGHJKLMNPRSTUVWXYZ';
$numeric = '123456789';
$rand_str = '';
for ($p = 0; $p < $countAlpha; $p++) {
$rand_str .= $alpha[mt_rand(0, strlen($alpha)-1)];
}
for ($p = 0; $p < $countNumeric; $p++) {
$rand_str .= $numeric[mt_rand(0, strlen($numeric)-1)];
}
if($randomize) {
$rand_str = str_split($rand_str);
shuffle($rand_str);
return implode($rand_str);
}
return $rand_str;
}
Inside I have 2 for loops, each one based on parameters $countAlpha and $countNumeric. I also have a 3rd parameter, $randomize that will allow you to randomize the output if you wish.
You could separe numbers and letter. Then, append N values of each into an array, shuffle it, and the implode to get your string:
function generate_random($nNumbers = 2, $nAlpha = 2) {
// prepare data to use
$num = '123456789';
$numlen = strlen($num) - 1;
$alpha = 'ABCDEFGHJKLMNPRSTUVWXYZ';
$alphalen = strlen($alpha) - 1;
$out = []; // New array
// generate N numbers
for ($i = 0; $i < $nNumbers ; $i++) {
$out[] = $num[mt_rand(0, $numlen)];
}
// generate N letters
for ($i = 0; $i < $nAlpha ; $i++) {
$out[] = $alpha[mt_rand(0, $alphalen)];
}
shuffle($out); // Shuffle the array
return implode($out); // Convert to string
}
echo generate_random() ;
// echo generate_random(2, 4) ; // example

How to generate a random pattern of *&# in PHP

Hello there i am making a program which will let me help generate a random string with a specified limit and random strings of *&# but then the combination of *&# should not repeat.
Ex: if I input 3 then the O/P should be
#**
**#
**#
It should generate a random string of length 3 up to 3 rows with different patterns also the pattern should not repeat. I am using the below code but not able to attain it.
$n = 3;
for($i = 0; $i < n; $i++)
{
for($j=0;$j<=$n;j++)
{
echo "*#";
}
echo "<br />";
}
But I am not able to generate the output, where is my logic failing?
If you want to make sure the same pattern doesn't show up more than once you'll have to keep a record of the generated strings. In the most basic form it could look like this:
public function generate() {
$amount = 3; // The amount of strings you want.
$generated_strings = []; // Keep a record of the generated strings.
do {
$random = $this->generateRandomString(); // Generate a random string
if(!in_array($random, $generated_strings)) { // Keep the record if its not already present.
$generated_strings[] = $random;
}
} while(sizeof($generated_strings) !== $amount); // Repeat this process until you have three strings.
print_r($generated_strings);
}
public function generateRandomString($length = 3) {
$characters = '*&#';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
Not necessarily the most optimized algorithm but it should work.
I am using a string generator, somewhat random, combining the chars you have provided. The second part is filling the output array with generated strings that are not already present.
<?php
function randomize($n) {
$s = '';
for ($i = 0; $i < $n; $i++) {
$s. = (rand(0, 10) < 5 ? '*' : '#');
}
return $s;
}
$n = 3;
$output = array();
for ($i = 0; $i < $n; $i++) {
$tmp = randomize($n);
while (in_array($tmp, $output)) {
$tmp = randomize($n);
}
$output[] = $tmp;
}
print_r($output);
Visible here
You can use a while loop and array unique to do this.
I first have an array with possible chars.
Then I loop until result array is desired lenght.
I use array unique to remove any duplicates inside the loop.
I use rand(0,2) to "select" a random character from possible characters array.
$arr = ["*", "&", "#"];
$res = array();
$n =7;
While(count($res) != $n){
$temp="";
For($i=0;$i<$n;$i++){
$temp .= $arr[Rand(0,count($arr)-1)];
}
$res[] = $temp;
$res = array_unique($res);
}
Var_dump($res);
https://3v4l.org/Ko4Wd
Updated with out of scope details not clearly specified by OP.

php get string length and replace first and last 3 characters WITHOUT using a function

I am trying to get the length of a string and replace its first and last 3 characters with a star sign (*) and get the string length WITHOUT using any PHP build in functions.
strlen - substr - preg_replace
Example: $string = "123456789"; $new_string = "***456***";
Is it possible?
I have checked many tutorials and couldn't figure it out. Please help. Thanks!
Universal solution:
$string = "123456789";
$i = 0;
$limit = 3;
while (isset($string[$i])) {
if ($i < $limit) {
$string[$i] = '*';
}
$i++;
}
// you can rewrite this as loop
$string[$i - 1] = '*';
$string[$i - 2] = '*';
$string[$i - 3] = '*';
Starting with php7.1 where negative string indexes are allowed:
$string = "123456789";
// you can rewrite it to a loop too
$string[0] = $string[1] = $string[2] = $string[-1] = $string[-2] = $string[-3] = '*';
echo $string;
Solution without any function, but it emits PHP Notice, you can supress it with #:
$string = "123456789";
$i = 0;
$limit = 3;
while (true) {
if ($string[$i] == '') {
break;
}
if ($i < $limit) {
$string[$i] = '*';
}
$i++;
}
/* Simplified version:
while ($string[$i] != '') {
if ($i < $limit) {
$string[$i] = '*';
}
$i++;
}
*/
$string[$i - 1] = '*';
$string[$i - 2] = '*';
$string[$i - 3] = '*';
echo $string;
I don't know why you don't want to use any PHP functions. However, it is still possible.
<?php
function privacy($string)
{
//get the string length
$i = 0;
/*
while (isset($string[$i])) {
$i++;
}
*/
while ($string[$i] !== "") {
$i++;
}
//replace the first and last 3 characters of the $string with a star
//if the length is bigger than or equals to 6
if ($i >= 6) {
for ($x = 0; $x < 3; $x++) {
$string[$x] = "*";
$string[$i - $x] = "*";
}
}
return $i . "<br>" . $string;
}
echo privacy("123456789");
?>
Will echo out this
9
***456***
I think it is the easiest way to get the string length and replace the first and last 3 characters without confusion. So far!
Good luck!
You can simply achieve it usong loop.(No built-in function)
$string = "123456789";
$i = 0;
$new_str = "";
while(true)
{
$val = #$string[$i];
if($val == "")
break;
if($i<3)
$new_str .= "*";
else
$new_str .= $val;
$i++;
}
for($j=0;$j<$i;$j++)
{
if($j >= ($i-3))
$new_str[$j]="*";
}
echo $new_str;
DEMO
you can access a string like you would access an array.
$var = "leroy jenkins";
$var[2] = 'd';
var_dump($var); // "ledoy jenkins"
but I'm currently not sure how to get the last 3 without using a build in function

Creating licence plates from different but similar strings

I need help to create a licence plate (6 character length) from different equal or unequal length of strings.
Example 1:
$str1 = "YE37";
$str2 = "TE37";
$str3 = "LYTE";
When I combine, it should give me "LYTE37". I must use all of them to formulate a plate. I can find the common longest sequence between $str1 and $str2 is "E37" but unsure "Y" or "T" comes first (i.e., whether "YTE37" or "TYE37")" then I can combine with $str3 using the longest common sequence ("YTE") which supposed to give me "LYTE37".
Example 2: "YLF3", "EYLF" and "YLF37" should give me "EYLF37".
I use the following function that finds the longest common sequence
$string_1="YE37";
$string_2="TE37";
$S =get_longest_common_subsequence($string_1, $string_2); // $S is "E37"
function get_longest_common_subsequence($string_1, $string_2)
{
$string_1_length = strlen($string_1);
$string_2_length = strlen($string_2);
$return = '';
if ($string_1_length === 0 || $string_2_length === 0)
{
// No similarities
return $return;
}
$longest_common_subsequence = array();
// Initialize the CSL array to assume there are no similarities
$longest_common_subsequence = array_fill(0, $string_1_length, array_fill(0, $string_2_length, 0));
$largest_size = 0;
for ($i = 0; $i < $string_1_length; $i++)
{
for ($j = 0; $j < $string_2_length; $j++)
{
// Check every combination of characters
if ($string_1[$i] === $string_2[$j])
{
// These are the same in both strings
if ($i === 0 || $j === 0)
{
// It's the first character, so it's clearly only 1 character long
$longest_common_subsequence[$i][$j] = 1;
}
else
{
// It's one character longer than the string from the previous character
$longest_common_subsequence[$i][$j] = $longest_common_subsequence[$i - 1][$j - 1] + 1;
}
if ($longest_common_subsequence[$i][$j] > $largest_size)
{
// Remember this as the largest
$largest_size = $longest_common_subsequence[$i][$j];
// Wipe any previous results
$return = '';
// And then fall through to remember this new value
}
if ($longest_common_subsequence[$i][$j] === $largest_size)
{
// Remember the largest string(s)
$return = substr($string_1, $i - $largest_size + 1, $largest_size);
}
}
// Else, $CSL should be set to 0, which it was already initialized to
}
}
// Return the list of matches
return $return;
}
I need an algorithm that uses these strings and creates a licence plate.
Could this be the Algorithm you are looking for? Quick-Test Here.
<?php
$str1 = "YE37";
$str2 = "TE37";
$str3 = "LYTE";
$strA = "YLF3";
$strB = "EYLF";
$strC = "YLF37";
function generatePlateNumber($str1, $str2, $str3) {
$plateNumber = '';
$arr = array($str1, $str2, $str3);
$arrStr = array();
foreach($arr as $str){
if(!preg_match("#\d#", $str)){
$arrStr[] = $str;
}
}
foreach($arr as $str){
if(preg_match("#\d#", $str)){
$arrStr[] = $str;
}
}
$chars = array_merge(str_split($arrStr[0]),
str_split($arrStr[1]),
str_split($arrStr[2]) );
$alphabets = [];
$numbers = [];
foreach($chars as $char){
if(is_numeric($char)){
$numbers[] = $char;
}else{
$alphabets[] = $char;
}
}
$alphabets = array_unique($alphabets);
$numbers = array_unique($numbers);
// BUILD THE PLATE NUMBER:
$plateNumber .= implode($alphabets) . implode($numbers);
return $plateNumber;
}

PHP For Loop strange issue

Any reason why this code sometimes only generates 4 character strings?
function genID()
{
$id = '';
$values = '0123456789abcdefghijklmnopqrstuvwxyz';
for($i=0; $i < 5; $i++) :
$str = substr($values, rand(0, strlen($values)), 1);
if(!is_nan(acos($str)))
(mt_rand(0, 1)) ? $str = strtoupper($str) : '';
$id .= $str;
endfor;
return $id; // e.g: ifR8j
}
acos($str) accepts numbers not string.... if u remove the aphabets from the string
ie.
$values = '0123456789abcdefghijklmnopqrstuvwxyz';
to
$values = '0123456789';
you will get the length as 5... Hope this helps..
Try, something simple:
function genID() {
$id = '';
$i = $length = 4;
$possible = "0123456789bcdfghjkmnpqrstvwxyz";
$possibleChar = strlen($possible) - 1;
while ($i) {
$char = $possible[mt_rand(0, $possibleChar)];
while (!strstr($id, $char)) {
$id .= $char;
$i--;
}
}
return $id;
}
(mt_rand(0, 1)) ? $str = strtoupper($str) : '';
This condition is met so sometimes you get an empty char.
Fix the condition or do the loop in some other manner.
For example
while(strlen($id)<5) {
//do the loop
}
The loop iterates 5 times.
rand will also return strlen, so $str will sometimes be ""
$str = substr($values, rand(0, strlen($values))-1, 1);
This will generate 5 characters always.

Categories