generate a meaningful random string using php - 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

Related

Why is function rand in square brackets?

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.

PHP - How to get the string between two specific characters

I got now a two sides that contains numbers and between two specific numbers there is a string that shows a group of numbers, Let's say we got this 123456789$numbers1234567 and I want to get the result of $numbers so how can I get it?
Thanks
If you know the two strings that it is sandwiched between then you can strip out the strings that you are looking for.
Not too elegant but this works:
$str1 = "123456789";
$str2 = "1234567";
$numberstr = "123456789";
$searchstring = "123456789".$numberstr."1234567";
$limit = 1;
$numbers = substr($searchstring, 0, strlen($searchstring) - strlen($str2)); // Remove the end of the string with length = $str2
$numbers = substr($numbers, strlen($numbers) - strlen($str1)); // Remove the most string from the beginning
print $numbers;
Output:
123456789
In summary, it removes the known string from the end, then the other known string from the beginning.
UPDATE: as per the comments, use two substrs to find the wanted string

How to adjusting string length

I am trying to limit the characters of a string. Additionally, if the string is less than the required characters, I want to add padding to it.
function create_string($string, $length) {
$str_len = strlen($string);
if($str_len > $length) {
//if string is greater than max length, then strip it
$str = substr($string, 0, $length);
} else {
//if string is less than the required length, pad it with what it needs to be the length
$remaining = $length-$str_len;
$str = str_pad($string, $remaining);
}
return $str;
}
My input is
"Nik's Auto Salon"
which is 16 characters. The second parameter is 40.
However, This string is returned
"Nik's Auto Salon "
which has only eight characters of padding added onto it. That doesn't seem right.
I also tried this string:
Gold Package Mobile Car Detail
With this input, it returns a string with NO padding added onto it. When that phrase is shorter than the required 45 length I put in the second parameter place.
How can I make this function work according to my specifications?
str_pad doesn't add spaces equal to its second parameter, it pads the string TO the length given in the second parameter. This isn't very clear even in the documentation.
Try this instead (and take out the line where you calculate $remaining):
$str = str_pad($string, $length);

Random String Generator (PHP)

I am trying write a PHP function that returns a random string of a given length. I wrote this:
<?
function generate_string($lenght) {
$ret = "";
for ($i = 0; $i < $lenght; $i++) {
$ret .= chr(mt_rand(32,126));
}
return $ret;
}
echo generate_string(150);
?>
The above function generates a random string, but the length of the string is not constant, ie: one time it is 30 characters, the other is 60 (obviously I call it with the same length as input every time). I've searched other examples of random string generators, but they all use a base string to pick letters. I am wondering why this method is not working properly.
Thanks!
Educated guess: you attempt to display your plain text string as HTML. The browser, after being told it's HTML, handles it as such. As soon as a < character is generated, the following characters are rendered as an (unknown) HTML tag and are not displayed as HTML standards mandate.
Fix:
echo htmlspecialchars(generate_string(150));
This is the conclusion i reached after testing it a while : Your functions works correctly. It depends on what you do with the randomly generated string. If you are simply echo-ing it, then it might generate somthing like <ck1ask which will be treated like a tag. Try eliminating certain characters from being concatenated to the string.
This function will work to generate a random string in PHP
function getRandomString($maxlength=12, $isSpecialChar=false)
{
$randomString=null;
//initalise the string include lower case, upper case and numbers
$charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
//if required special character to include, please set $isSpecialchar= 1 or true
if ($isSpecialChar) $charSet .= "~##$%^*()_±={}|][";
//loop for get specify length character with random characters
for ($i=0; $i<$maxlength; $i++) $randomString .= $charSet[(mt_rand(0, (strlen($charSet)-1)))];
//return the random string
return $randomString;
}
//call the function set value you required to string length default:12
$random8char=getRandomString(8);
echo $random8char;
Source: Generate random string in php

Convert substr filter from character count to word count

I'm using the getExcerpt() function below to dynamically set the length of a snippet of text. However, my substr method is currently based on character count. I'd like to convert it to word count. Do I need to separate function or is there a PHP method that I can use in place of substr?
function getExcerpt()
{
//currently this is character count. Need to convert to word count
$my_excerptLength = 100;
$my_postExcerpt = strip_tags(
substr(
'This is the post excerpt hard coded for demo purposes',
0,
$my_excerptLength
)
);
return ": <em>".$my_postExcerpt." [...]</em>";}
}
Use str_word_count
Depending on the parameters, it can either return the number of words in a string (default) or an array of the words found (in case you only want to use a subset of them).
So, to return the first 100 words of a snippet of text:
function getExcerpt($text)
{
$words_in_text = str_word_count($text,1);
$words_to_return = 100;
$result = array_slice($words_in_text,0,$words_to_return);
return '<em>'.implode(" ",$result).'</em>';
}
If you want that your script should not ignore the period and comma and other punctuation symbols then you should adopt this approach.
function getExcerpt($text)
{
$my_excerptLength = 100;
$my_array = explode(" ",$text);
$value = implode(" ",array_slice($my_array,0,$my_excerptLength));
return
}
Note : This is just an example.Hope it will help you.Don't forget to vote if it help you.

Categories