I want to capitalize random letters in a string and echo the complete sentence from hello69.world to HeLlO69.WoRlD. Each time the functions run, it should capitalize random letters and exclude special characters and digits. I've tried this so far but it only selects the first 5 characters in string every time and outputs only Capitalized letters. How to fix this?
<?php
$string = "hellohg.09ui8vkosjbdh";
$selchr = substr($string,0, 5);
$caps = strtoupper($selchr);
echo substr_replace($string, $caps,0);
?>
Let's assume you want to CAPITALIZE 5 letters randomly:
$string = "hellohg.09ui8vkosjbdh";
$characters = str_split($string);
$i = 0;
do{
$random_index = rand(0, count($characters) - 1);
$unique_indices[] = ""; //UNIQUE INDICES
while (in_array($random_index, $unique_indices)) {
$random_index = rand(0, count($characters) - 1);
}
$unique_indices[] = $random_index;
$random_letter = $characters[$random_index];
if(ctype_alpha($random_letter)){//only letters
$characters[$random_index] = strtoupper($random_letter);
$i++;
}
}while($i<5);echo implode('', $characters);
Thanks to #El_Vanja for Note UNIQUE INDICES
Related
I am looking for an approach like mt_rand to generate a random value, but between two alphanumeric values instead of integers.
For example, rand(g3j3j4k5, z9kDDkks8f8d).
I tried to convert the alphanumeric values to integers by base_convert. Beside the fact, it is somehow overkill, sometimes the integer is more than 15 digits, and thus not working in PHP rand functions.
NOTE: It is not about making a random string with given length. The value should between two given values, exactly like a random number between min and max integers.
This should work for you:
Here I split $min and $max into an array with str_split() and loop through each character of both arrays with array_map().
There I get the position of the character with strpos() and return a random alphanum character in that particular range. If min is bigger than max I just return a random character from the entire range.
Code:
<?php
function alphanum_rand($min = "", $max = ""){
$chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$random = array_map(function($minC, $maxC)use($chars){
if(($minKey = strpos($chars, $minC)) < ($maxKey = strpos($chars, $maxC)))
return $chars[mt_rand($minKey, $maxKey)];
else
return $chars[mt_rand(0, strlen($chars))];
}, str_split($min), str_split($max));
return implode("", $random);
}
echo alphanum_rand("g3j3j4k5", "z9kDDkks8f8d");
?>
You could try a simple PHP Function and define a random string alpha numeric and can also include special characters. For loop will do the magic for u :)
function RandomString($size)
{
$chars = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$string = array();
$alphaLength = strlen($chars) - 1;
for ($i = 0; $i < $size; $i++) {
$n = rand(0, $alphaLength);
$string[] = $chars[$n];
}
return implode($string);
}
and simple call it with the size you need.
<?php
echo RandomString(5); // Length of strings
?>
In PHP, how to convert a string containing mixture of random letters and numbers to a string containing serial numbers along with random numbers without changing their position in a string? For example,
$str_a = "1)Apple 5)Ball 3)Cat 8)Dog 4)Egg";
Now, I want to convert this string into
$str_b = "1)Apple 2)Ball 3)Cat 4)Dog 5)Egg";
I want the numbers 1,5,3,8,4 to be 1,2,3,4,5.
This should work for you:
Just use preg_replace_callback() and replace each digit (\d+ => 0-9 as many times as possible) with an incrementing number, .e.g
<?php
$str_a = "1)Apple 5)Ball 3)Cat 8)Dog 4)Egg";
$start = 1;
echo $newStr = preg_replace_callback("/\d+/", function($m)use(&$start){
return $start++;
}, $str_a);
?>
output:
1)Apple 2)Ball 3)Cat 4)Dog 5)Egg
Created Simple looping program:
$str_a = "1)Apple 5)Ball 3)Cat 8)Dog 4)Egg";
function change($str_a) {
$counter = 1;
for($i=0; $i<strlen($str_a); $i++) {
if(is_numeric($str_a[$i])) {
$str_a[$i] = $counter++;
}
}
return $str_a;
}
print(change($str_a))
Output:
1)Apple 2)Ball 3)Cat 4)Dog 5)Egg
You can use preg_split and then concatenate it incrementing by 1. This will work also for numbers consisting of multiple digits:
$str_a = "51)Apple 675)Ball 334)Cat 84)Dog 904)Egg";
$a = preg_split('/\b\d+/', $str_a);
$str_b = '';
for($i=0,$c = count($a);$i<$c;$i++){
if($i){
$str_b .= $i.$a[$i];
}
}
echo $str_b;
Output:
1)Apple 2)Ball 3)Cat 4)Dog 5)Egg
How can I shift characters of string in PHP by 5 spaces?
So say:
A becomes F
B becomes G
Z becomes E
same with symbols:
!##$%^&*()_+
so ! becomes ^
% becomes )
and so on.
Anyway to do this?
The other answers use the ASCII table (which is good), but I've got the impression that's not what you're looking for. This one takes advantage of PHP's ability to access string characters as if the string itself is an array, allowing you to have your own order of characters.
First, you define your dictionary:
// for simplicity, we'll only use upper-case letters in the example
$dictionary = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
Then you go through your input string's characters and replace each of them with it's $position + 5 in the dictionary:
$input_string = 'STRING';
$output_string = '';
$dictionary_length = strlen($dictionary);
for ($i = 0, $length = strlen($input_string); $i < $length; $i++)
{
$position = strpos($dictionary, $input_string[$i]) + 5;
// if the searched character is at the end of $dictionary,
// re-start counting positions from 0
if ($position > $dictionary_length)
{
$position = $position - $dictionary_length;
}
$output_string .= $dictionary[$position];
}
$output_string will now contain your desired result.
Of course, if a character from $input_string does not exist in $dictionary, it will always end up as the 5th dictionary character, but it's up to you to define a proper dictionary and work around edge cases.
Iterate over characters and, get ascii value of each character and get char value of the ascii code shifted by 5:
function str_shift_chars_by_5_spaces($a) {
for( $i = 0; $i < strlen($a); $i++ ) {
$b .= chr(ord($a[$i])+5);};
}
return $b;
}
echo str_shift_chars_by_5_spaces("abc");
Prints "fgh"
Iterate over string, character at a time
Get character its ASCII value
Increase by 5
Add to new string
Something like this should work:
<?php
$newString = '';
foreach (str_split('test') as $character) {
$newString .= chr(ord($character) + 5);
}
echo $newString;
Note that there is more than one way to iterate over a string.
PHP has a function for this; it's called strtr():
$shifted = strtr( $string,
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"FGHIJKLMNOPQRSTUVWXYZABCDE" );
Of course, you can do lowercase letters and numbers and even symbols at the same time:
$shifted = strtr( $string,
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!##$%^&*()_+",
"FGHIJKLMNOPQRSTUVWXYZABCDEfghijklmnopqrstuvwxyzabcde5678901234^&*()_+!##$%" );
To reverse the transformation, just swap the last two arguments to strtr().
If you need to change the shift distance dynamically, you can build the translation strings at runtime:
$shift = 5;
$from = $to = "";
$sequences = array( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz",
"0123456789", "!##$%^&*()_+" );
foreach ( $sequences as $seq ) {
$d = $shift % strlen( $seq ); // wrap around if $shift > length of $seq
$from .= $seq;
$to .= substr($seq, $d) . substr($seq, 0, $d);
}
$shifted = strtr( $string, $from, $to );
I want to swap 2 characters in a string with 2 other ones.
Start string = "`bHello `!how `Qare `%you."
Random string = "1234567890abcdefghijklmnopqrstuvwxyz!£$%^&#"
How do i swap `b `! `Q `% with random ones so it looks something like this
End result string = "`4Hello `^how `$are `#you."
I have tried this so far
I tried so far
$out = "`vHow `!are `#you."
$patterns = array("`1","`J","`2","`3","`4","`5","`6","`7","`!","`$","`%","`^","`&","`)","`~","`#","`#","`q","`e","`y","`t","`p","`j","`k","`l","`M","`x","`v","`m","`Q","`E","`R","`T","`Y","`P","`G","`K","`L","`X","`V");
$pretest = array("`1","`J","`2","`3","`4","`5","`6","`7","`!","`$","`%","`^","`&","`)","`~","`#","`#","`q","`e","`y","`t","`p","`j","`k","`l","`M","`x","`v","`m","`Q","`E","`R","`T","`Y","`P","`G","`K","`L","`X","`V");
$tempstr = $pretest[rand(0, strlen($pretest)-1)];
$substs = "`".$tempstr;
$out = preg_replace($patterns, $substs, $out);
However the end result is
$out = "`%How `%are `%you."
it picks only 1 random and changes them all to that one.
<?php
function randomChar() {
$rand = "1234567890abcdefghijklmnopqrstuvwxyz";
return substr($rand, rand(0, strlen($rand)), 1);
}
echo preg_replace_callback("/`./", 'randomChar', "`bHello `!how `Qare `%you.");
Hie guys i want to create a random string of numbers where there is a fixed letter B at the beginning and a set of eight integers ending with any random letter, like for example B07224081A where A and the other numbers are random. This string should be unique. How can I do this?
Do you mean something like this?
$letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$numbers = rand(10000000, 99999999);
$prefix = "B";
$sufix = $letters[rand(0, 25)];
$string = $prefix . $numbers . $sufix;
echo $string; // printed "B74099731P" in my case
The more characters - the greater chance to generate unique string.
I think that's much better method to use uniqid() since it's based on miliseconds. Uniqueness of generated string is guaranteed.
This should work for you.
$randomString = "B";
for ($i = 0; $i < 9; $i++) {
if ($i < 8) {
$randomString.=rand(0,9);
}
if ($i == 8) {
$randomString.=chr(rand(65,90));
}
}
echo $randomString;