Recursion with anonymous function [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
javascript: recursive anonymous function?
Anonymous recursive PHP functions
I was wondering... Is it possible to do recursion with anonymous function?
Here is one example: I need to get six-chars long string which may contain only numbers and spaces. The only rules are that it cannot start or end with spaces. We check for that and if that occurs - just call recursion on the same, anonymous, function. Just how!?
function() {
$chars = range(0, 9);
$chars[] = ' ';
length = 6;
$count = count($chars);
$string = '';
for ($i = 0; $i < $length; ++$i) {
$string .= $chars[mt_rand(0, $count - 1)];
}
$string = trim($string);
if (strlen($string) !== $length) { // There were spaces in front or end of the string. Shit!
// Do recursion.
}
return $string;
}

Yes it is, but I wouldn't recommend it as it's a bit tricky ;)
First possibility:
<?php
$some_var1="1";
$some_var2="2";
function($param1, $param2) use ($some_var1, $some_var2)
{
call_user_func(__FUNCTION__, $other_param1, $other_param2);
}
?>
Another one:
<?php
$recursive = function () use (&$recursive){
// The function is now available as $recursive
}
?>
Examples taken from http://php.net/

The answer is complicated but not impossible. It took me several minutes to figure out. We first must define a utility function called $combinator().
The solution to your problem:
$combinator(
function($self) { function() use (&$self) {
$chars = range(0, 9);
$chars[] = ' ';
length = 6;
$count = count($chars);
$string = '';
for ($i = 0; $i < $length; ++$i) {
$string .= $chars[mt_rand(0, $count - 1)];
}
$string = trim($string);
if (strlen($string) !== $length) {
return $self();
}
return $string;
} }
);
The definition of $combinator():
$combinator = function($principle)
{
(function($transept) use (&$principle)
{
$principle(
function($arguments) use (&$transept)
{
call_user_func_array($transept($transept), $arguments));
}
);
})
(function($transept) use (&$principle)
{
$principle(
function($arguments)
{
call_user_func_array($transept($transept), $arguments);
}
);
});
}

A much saner method to do the same thing. Requires only one loop as well.
$chars = array_merge(range(0, 9), array(' '));
$string = mt_rand(0, 9);
for ($i = 1; $i <= 4; $i++) {
$string .= $chars[array_rand($chars)];
}
$string .= mt_rand(0, 9);
Sorry for sidestepping the actual question though.

use goto
function() {
start:
$chars = range(0, 9);
$chars[] = ' ';
length = 6;
$count = count($chars);
$string = '';
for ($i = 0; $i < $length; ++$i) {
$string .= $chars[mt_rand(0, $count - 1)];
}
$string = trim($string);
if (strlen($string) !== $length) { // There were spaces in front or end of the string. Shit!
goto start;
}
return $string;
But it's not the best idea to use goto.

Related

How to create a user defined function in PHP exactly the same as str_replace(), without using any other built-in functions except for strlen()

<?php
echo my_string_replace("world","jonathan","hello world helloworld");
function my_string_replace($find, $replace, $string)
{
//Block of codes here...
}
?>
I can only use loops, if else statements, and other commands such as break and continue. I want to create my own algorithm. Please help me. This should output : hello jonathan hellojonathan"
error_reporting(0); used for hide "Uninitialized string offset" notice.
<?php
function str_v2($num){
error_reporting(0);
for($i=0; $num[$i] != "";$i++);
echo $i; }//end of function
$name = "Hope this will work.";
echo str_v2($name);
?>
That was a fun brain teaser. Here you go:
echo my_string_replace("world", "jonathan", "hello world helloworld");
function my_string_replace($find, $replace, $string)
{
$characterCount = strlen($string);
$findCount = strlen($find);
$replaceCount = strlen($replace);
for ($i = 0; $i < $characterCount - $findCount +1; $i++) {
if ($string[$i] == $find[0]) {
$j = 1;
$found = true;
while ($j < $findCount) {
if ($string[$i + $j] != $find[$j]) {
$found = false;
break;
}
$j++;
}
if ($found) {
// copy string until current position
$replaced = '';
for ($x = 0; $x < $i; $x++) {
$replaced .= $string[$x];
}
// append replacement
$replaced .= $replace;
// copy after match till end
for ($x = $i + $findCount; $x < $characterCount; $x++) {
$replaced .= $string[$x];
}
// continue with replaced string, after replacement
$string = $replaced;
$characterCount = strlen($string);
$i = $i + $replaceCount;
}
}
}
return $string;
}

How to replace multiple random characters in string with underscore(_) in PHP

I am using codes like "gjhyYhK", "HJjhkeuJ" etc. But want user to show these codes like:
gj_y__K
HJj__e_J
means code will be edited with "_" at random positions in code.
This will do what you want:
$str = "gjhyYhK";
$len = strlen($str);
$num_to_remove = ceil($len * .4); // 40% removal
for($i = 0; $i < $num_to_remove; $i++)
{
$k = 0;
do
{
$k = rand(1, $len);
} while($str[$k-1] == "_");
$str[$k-1] = "_";
}
print $str . "\n";
If you want more underscores, change the value of $underscores. This will guarantee you get how many underscores you want, so long as you want fewer than the length of the string
Try this:
$string=array(
'gjhyYhK',
'HJjhkeuJ'
);
$arr=array();
foreach ($string as $key=>$value) {
$arr[$key]='';
for ($i=1; $i <=strlen($value); $i++) {
if(rand(0,1)){
$arr[$key].=substr($string[$key],$i,1);
}else{
$arr[$key].='_';
}
}
}
var_dump($arr);
you can try below code to get the functionality what you are looking for
<?php
$string = "gjhyYhK";
$percentage = 40;
$total_length = strlen($string);
$number_of_underscore = floor(($percentage / 100) * $total_length); // I have use floor value, you can use ceil() as well
for ($i = 1; $i <= $number_of_underscore; $i++)
{
$random_position = rand(0, strlen($string) - 1); // get the random position of character to be replaced
if (substr($string, $random_position, 1) !== '_') // check if its already replaced underscore (_)
{
$string = preg_replace("/" . (substr($string, $random_position, 1)) . "/", '_', $string, 1); // here preg_replaced use to replace the character only once, (i.e str_replace() will replace all matching characters)
}
else
{
$i--; // else decrement $i for the loop to run one more time
}
}
echo $string;
?>
let me know if any other help needed
$str = "ADFJ";
$strlen = strlen($str);
$newStr = '';
for ($i = 0; $i < $strlen; $i++) {
if ($i == rand(0, $strlen)) {
$newStr .= '_';
} else {
$newStr .= $str[$i];
}
}
echo $newStr;

Optimal function to create a random UTF-8 string in PHP? (letter characters only)

I wrote this function that creates a random string of UTF-8 characters. It works well, but the regular expression [^\p{L}] is not filtering all non-letter characters it seems. I can't think of a better way to generate the full range of unicode without non-letter characters.. short of manually searching for and defining the decimal letter ranges between 65 and 65533.
function rand_str($max_length, $min_length = 1, $utf8 = true) {
static $utf8_chars = array();
if ($utf8 && !$utf8_chars) {
for ($i = 1; $i <= 65533; $i++) {
$utf8_chars[] = mb_convert_encoding("&#$i;", 'UTF-8', 'HTML-ENTITIES');
}
$utf8_chars = preg_replace('/[^\p{L}]/u', '', $utf8_chars);
foreach ($utf8_chars as $i => $char) {
if (trim($utf8_chars[$i])) {
$chars[] = $char;
}
}
$utf8_chars = $chars;
}
$chars = $utf8 ? $utf8_chars : str_split('abcdefghijklmnopqrstuvwxyz');
$num_chars = count($chars);
$string = '';
$length = mt_rand($min_length, $max_length);
for ($i = 0; $i < $length; $i++) {
$string .= $chars[mt_rand(1, $num_chars) - 1];
}
return $string;
}
\p{L} might be catching too much. Try to limit to {Ll} and {LU} -- {L} includes {Lo} -- others.
With PHP7 and IntlChar there is now a better way:
function utf8_random_string(int $length) : string {
$r = "";
for ($i = 0; $i < $length; $i++) {
$codePoint = mt_rand(0x80, 0xffff);
$char = \IntlChar::chr($codePoint);
if ($char !== null && \IntlChar::isprint($char)) {
$r .= $char;
} else {
$i--;
}
}
return $r;
}

PHP Random Number

I want to generate a random number in PHP where the digits itself should not repeat in that number.
Is that possible?
Can you paste sample code here?
Ex: 674930, 145289. [i.e Same digit shouldn't come]
Thanks
Here is a good way of doing it:
$amountOfDigits = 6;
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $amountOfDigits;$i++)
$digits .= $numbers[$i];
echo $digits; //prints 217356
If you wanted it in a neat function you could create something like this:
function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
function randomize($len = false)
{
$ints = array();
$len = $len ? $len : rand(2,9);
if($len > 9)
{
trigger_error('Maximum length should not exceed 9');
return 0;
}
while(true)
{
$current = rand(0,9);
if(!in_array($current,$ints))
{
$ints[] = $current;
}
if(count($ints) == $len)
{
return implode($ints);
}
}
}
echo randomize(); //Numbers that are all unique with a random length.
echo randomize(7); //Numbers that are all unique with a length of 7
Something along those lines should do it
<?php
function genRandomString() {
$length = 10; // set length of string
$characters = '0123456789'; // for undefined string
$string ="";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
$s = genRandomString(); //this is your random print var
or
function rand_string( $length )
{
$chars = "0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ )
{
$str .= $chars[ rand( 0, $size – 1 ) ];
}
return $str;
}
$rid= rand_string( 6 ); // 6 means length of generate string
?>
$result= "";
$numbers= "0123456789";
$length = 8;
$i = 0;
while ($i < $length)
{
$char = substr($numbers, mt_rand(0, strlen($numbers)-1), 1);
//prevents duplicates
if (!strstr($result, $char))
{
$result .= $char;
$i++;
}
}
This should do the trick. In $numbers you can put any char you want, for example: I have used this to generate random passwords, productcodes etc.
The least amount of code I saw for something like this was:
function random_num($n=5)
{
return rand(0, pow(10, $n));
}
But I'm assuming it requires more processing to do this than these other methods.

Generating (pseudo)random alpha-numeric strings

How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?
First make a string with all your possible characters:
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
You could also use range() to do this more quickly.
Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your string:
$string = '';
$max = strlen($characters) - 1;
for ($i = 0; $i < $random_string_length; $i++) {
$string .= $characters[mt_rand(0, $max)];
}
$random_string_length is the length of the random string.
I like this function for the job
function randomKey($length) {
$pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));
for($i=0; $i < $length; $i++) {
$key .= $pool[mt_rand(0, count($pool) - 1)];
}
return $key;
}
echo randomKey(20);
Generate cryptographically strong, random (potentially) 8-character string using the openssl_random_pseudo_bytes function:
echo bin2hex(openssl_random_pseudo_bytes(4));
Procedural way:
function randomString(int $length): string
{
return bin2hex(openssl_random_pseudo_bytes($length));
}
Update:
PHP7 introduced the random_x() functions which should be even better. If you come from PHP 5.X, use excellent paragonie/random_compat library which is a polyfill for random_bytes() and random_int() from PHP 7.
function randomString($length)
{
return bin2hex(random_bytes($length));
}
One line solution:
echo substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 7 );
You can change the substr parameter in order to set a different length for your string.
Use the ASCII table to pick a range of letters, where the: $range_start , $range_end is a value from the decimal column in the ASCII table.
I find that this method is nicer compared to the method described where the range of characters is specifically defined within another string.
// range is numbers (48) through capital and lower case letters (122)
$range_start = 48;
$range_end = 122;
$random_string = "";
$random_string_length = 10;
for ($i = 0; $i < $random_string_length; $i++) {
$ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range
// finds the character represented by $ascii_no and adds it to the random string
// study **chr** function for a better understanding
$random_string .= chr( $ascii_no );
}
echo $random_string;
See More:
chr function
mt_rand function
I know it's an old post but I'd like to contribute with a class I've created based on Jeremy Ruten's answer and improved with suggestions in comments:
class RandomString
{
private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
private static $string;
private static $length = 8; //default random string length
public static function generate($length = null)
{
if($length){
self::$length = $length;
}
$characters_length = strlen(self::$characters) - 1;
for ($i = 0; $i < self::$length; $i++) {
self::$string .= self::$characters[mt_rand(0, $characters_length)];
}
return self::$string;
}
}
Simple guys .... but remember each byte is random between 0 and 255 which for a random string will be fine. Also remember you'll have two characters to represent each byte.
$str = bin2hex(random_bytes(32)); // 64 character string returned
Maybe I missed something here, but here's a way using the uniqid() function.
I have made the following quick function just to play around with the range() function. It just might help someone sometime.
Function pseudostring($length = 50) {
// Generate arrays with characters and numbers
$lowerAlpha = range('a', 'z');
$upperAlpha = range('A', 'Z');
$numeric = range('0', '9');
// Merge the arrays
$workArray = array_merge($numeric, array_merge($lowerAlpha, $upperAlpha));
$returnString = "";
// Add random characters from the created array to a string
for ($i = 0; $i < $length; $i++) {
$character = $workArray[rand(0, 61)];
$returnString .= $character;
}
return $returnString;
}
You can use the following code. It is similar to existing functions except that you can force special character count:
function random_string() {
// 8 characters: 7 lower-case alphabets and 1 digit
$character_sets = [
["count" => 7, "characters" => "abcdefghijklmnopqrstuvwxyz"],
["count" => 1, "characters" => "0123456789"]
];
$temp_array = array();
foreach ($character_sets as $character_set) {
for ($i = 0; $i < $character_set["count"]; $i++) {
$random = random_int(0, strlen($character_set["characters"]) - 1);
$temp_array[] = $character_set["characters"][$random];
}
}
shuffle($temp_array);
return implode("", $temp_array);
}
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
echo generateRandomString();
If you want a very easy way to do this, you can lean on existing PHP functions. This is the code I use:
substr( sha1( time() ), 0, 15 )
time() gives you the current time in seconds since epoch, sha1() encrypts it to a string of 0-9a-f, and substr() lets you choose a length. You don't have to start at character 0, and whatever the difference is between the two numbers will be the length of the string.
First list the desired characters
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
Use the str_shuffle($string) function. This function will provide you a randomly shuffled string.
$alpha=substr(str_shuffle($chars), 0, 50);
50 is the Length of string.
This is something I use:
$cryptoStrong = true; // can be false
$length = 16; // Any length you want
$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);
$randomString = bin2hex($bytes);
You can see the Docs for openssl_random_pseudo_bytes here, and the Docs for bin2hex here
Jeremy's answer is great. If, like me, you're unsure of how to implement range(), you can see my version using range().
<?php
$character_array = array_merge(range('a', 'z'), range(0, 9));
$string = "";
for($i = 0; $i < 6; $i++) {
$string .= $character_array[rand(0, (count($character_array) - 1))];
}
echo $string;
?>
This does the exact same thing as Jeremy's but uses merged arrays where he uses a string, and uses count() where he uses strlen().
1 line:
$FROM = 0; $TO = 'zzzz';
$code = base_convert(rand( $FROM ,base_convert( $TO , 36,10)),10,36);
echo $code;
The modern way to do that with type hint / rand_int for real randomeness
function random_string(int $size): string
{
$characters = array_merge(
range(0, 9),
range('A', 'Z')
);
$string = '';
$max = count($characters) - 1;
for ($i = 0; $i < $size; $i++) {
$string .= $characters[random_int(0, $max)];
}
return $string;
}
public function randomString($length = 8)
{
$characters = implode([
'ABCDEFGHIJKLMNOPORRQSTUWVXYZ',
'abcdefghijklmnoprqstuwvxyz',
'0123456789',
//'!##$%^&*?'
]);
$charactersLength = strlen($characters) - 1;
$string = '';
while ($length) {
$string .= $characters[mt_rand(0, $charactersLength)];
--$length;
}
return $string;
}

Categories