Why is function rand in square brackets? - php

I cant figure out why is rand in square brackets in this case , everywhere I have checked it is in round ones. This is the code :
$characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$allCharacters=$characters . strtolower($characters);
$pass="";
for($i=0; $i<strlen($allCharacters);$i++)
$pass.=$allCharacters[rand (0,strlen($allCharacters)-1)] ;
echo $pass;

Welcome to Stack Overflow! :)
rand() is a function but it is just written with a space, to become rand ().
Here's an explanation:
$pass .= $allCharacters[rand(0, strlen($allCharacters) - 1)];
What this line is doing is:
Find the length of $allCharacters.
Pick a random number between 0 and one less than that number (51, if you're using the alphabet capital + lower).
Use that randomly generated number as an index to $allCharacters. This is what the square brackets are. Just as you'd get the third item of a list with $list[2] ($list[3 - 1]), you can use a random number as well. Whoever wrote this code is simply passing the result of rand() directly into the index.
That index will select a random character from your list of every character and append it to $pass.
So, what you'll end up with is $pass holding 52 random letters from the alphabet.

Related

Getting 2 random letters sequentially from a string

So getting 2 random letters from a string is easy enough to find an answer to:
$var1 = substr(str_shuffle(str_repeat($var1, 2)), 0, 2);
But what if you want to get 2 letters sequentially from a string,Is there a way to do it without using a loop?
For instance, if you have a string named "Colorado", and if the first random character grabbed was "r", it would only get a letter from the remaining 3 letters for the 2nd chosen letter.
There is most likely other ways, here is one.
Pick random char, use stristr, shuffle it then grab first 2 chars.
<?php
$var = 'Colorado';
// pick random
$picked = $var[rand(0, strlen($var))];
// grab string after first occurrence
$parts = stristr($var, $picked);
// shuffle it
$part = str_shuffle($parts);
echo $part[0].$part[1];
https://3v4l.org/uDvRX
*your need to add some undefined checks to handle no matches etc

PHP detect variable length string contains any character other than 1

Using PHP I sometimes have strings that look like the following:
111
110
011
1111
0110012
What is the most efficient way (preferably without regex) to determine if a string contains any character other then the character 1?
Here's a one-line code solution that can be put into a conditional etc.:
strlen(str_replace('1','',$mystring))==0
It strips out the "1"s and sees if there's anything left.
User Don't Panic commented that str_replace could be replaced by trim:
strlen(trim($mystring, '1'))==0
which removes leading and trailing 1s and sees if there's anything left. This would work for the particular case in OP's request but the first option will also tell you how many non-"1" characters you have (if that information matters). Depending on implementation, trim might run slightly faster because PHP doesn't have to check any characters between the first and last non-"1" characters.
You could also use a string like a character array and iterate through from the beginning until you find a character which is not =='1' (in which case, return true) or reach the end of the array (in which case, return false).
Finally, though OP here said "preferably without regex," others open to regexes might use one:
preg_match("/[^1]/", $mystring)==1
Another way to do it:
if (base_convert($string, 2, 2) === $string) {
// $string has only 0 and 1 characters.
}
since your $string is basically a binary number, you can check it with base_convert.
How it works:
var_dump(base_convert('110', 2, 2)); // 110
var_dump(base_convert('11503', 2, 2)); // 110
var_dump(base_convert('9111111111111111111110009', 2, 2)); // 11111111111111111111000
If the returned value of base_convert is different from the input, there're something other characters, beside 0 and 1.
If you want checks if the string has only 1 characters:
if(array_sum(str_split($string)) === strlen($string)) {
// $string has only 1 characters.
}
You retrieve all the single numbers with str_split, and sum them with array_sum. If the result isn't the same as the length of the string, then you've other number in the string beside 1.
Another option is treat string like array of symbols and check for something that is not 1. If it is - break for loop:
for ($i = 0; $i < strlen($mystring); $i++) {
if ($mystring[$i] != '1') {
echo 'FOUND!';
break;
}
}

Regular Expressions - preg or substr?

I have several values(strings mostly) which I want to process and I was wondering which way is the best to use in my case.
What I will have will be a foreach loop in which I want to have a check and insert into the database edited values.
Structure example:
foreach($values as $value)
{
//string check is going to be here
// .....
//insert the data into the database
$sql = "INSERT INTO results VALUES ('', 'xx', 'xx', 'xx', 'xx')";
$result = mysql_query($sql);
}
Example of values I might get:
value, value
Somewhere in the universe
3.532523, -55.523525
value - value
What I want to do is not accept (actually change their value to 'Not given')
a) numbers
b) strings longer than 10 characters
c) no spaces between the words
d) if there is a , or - only keep the first part of the string before these
A string check which I am testing for example is if I have a value like this
=> string, string
I only want to keep the first part, which is done by
$str = value, value $str = substr($str, 0, stripos($str, ','));
With which technique I will be able to do all these checks better? (preg_match & replace or substr & stipos)
This regex may match what you want to keep, but will allow numbers and _:
/^\w{,10}/
Fix numbers allowed with a negative lookahead and avoids _:
/^(?=\d{,9}[a-zA-Z])[a-zA-Z]{,10}/
If digits are not allowed at all:
/^[a-zA-Z]{,10}/

generate a meaningful random string using php

I would like to generate a random string with meaningful word
function randString($length, $charset='abcdefghijklmnopqrstuvwxyz'){
$str = '';
$count = strlen($charset);
while ($length--) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str;
}
I have used this function but it generate random which has not any meaning in dictionary.
Have you any idea or is it not possible.
Please let me know if you have any idea according or have better solution regarding.
Thanks in advance.
Try this for a random alphanumeric string
function get_random_string($valid_chars, $length) {
$random_string = '';
//Count the number of chars in the valid chars string so we know how many choices we have
$num_valid_chars = strlen($valid_chars);
//Repeat the steps until we've created a string of the right length
for($i=0;$i<$length;$i++) {
//Pick a random number from 1 up to the number of valid chars
$random_pick = mt_rand(1, $num_valid_chars);
//Take the random character out of the string of valid chars
//Subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
$random_char = $valid_chars[$random_pick-1];
$random_string .= $random_char;
}
return $random_string;
}
As Mark Baker writes in the comments, "meaningful" and "random" are hard to bring together.
However, if you want to show a real word, from a given language, without someone being able to guess in advance what that word will be, you would do it as follows (in pseudocode, don't have time to write it out as PHP):
read list of unique words in language into wordList
generate random integer i, <= length of wordList
return word at position i in wordList
Consider using a password dictionary as the source of your wordlist.
Get a list of words from ASPELL or http://sourceforge.net/projects/wordlist/, importing them into a db table and randomly select one by php :)
Sample query:
SELECT word FROM dictionary order by RAND() LIMIT 1

Big numbers regex

$value = preg_replace("/[^0-9]+/", '', $value);
How could I edit this regex to get rid of everything after the decimal point? There may or may not be a decimal point.
Currently "100.1" becomes 1001 but it should be 100.
Complete function:
function intfix($value)
{
$value = preg_replace("/[^0-9]+/", '', $value);
$value = trim($value);
return $value + 0;
}
It is used to format user input for numbers as well as servers output to format numbers for the DB. The functions deals with very large numbers, so I can't use intval or similar. Any extra comments to improve this function are welcome.
You could just change the regex to /[^0-9].*/s.
.* matches zero or more characters, so the first character that is not a digit, and the digits that immediately follow, would be deleted.
You need to have a pattern that starts the search with a decimal place. At the moment you're only deleting the . not the numbers after it... So you could do '/\.[\d]+/'
$text = "1201.21 12 .12 12.21";
$text = preg_replace('/\.[\d]+/', '' ,$text);
The above code would result in $text = "1201 12 12"
Why not $value = round($value, 0);? This can handle large values and is meant to get rid of the following decimals mathematically (I'd rather work with numbers as numbers not as strings). You can pass PHP_ROUND_HALF_DOWN as a third parameter if you want to just get rid of the decimals 10.7 -> 10. Or floor($value); could work too.

Categories