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
Related
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.
I am new to php and trying out some different things.
I got a problem with printing a random value from a string from multiply values.
$list = "the weather is beautiful tonight".
$random = one random value from $list, for example "beautiful" or "is"
Is there any simple way to get this done?
Thanks!
well, as #Dagon suggested, you can use explode() to get an array of strings, then you can use rand($min, $max) to get an integer between 0 and the length of your array - 1. and then read the string value inside your array at the randomly generated number position.
// First, split the string on spaces to get individual words
$arg = explode(' ',"the weather is beautiful tonight");
// Shuffle the order of the words
shuffle($arg);
// Display the first word of the shuffled array
print $arg[0];
I have a string called $metar
$metar = EICK 011300Z 10004KT 27/17 Q1018 TEMPO AT0800 20006KT 010V220 9999 SCT029
and this string could changed every an hour depending a dynamic file.
in basic, i want to separate the $metar to two strings, the separate point is "AT0800"
list($a, $b) = explode(' AT0800 ', $metar);
echo $b;
but the problem is the "AT0800" could change to "AT1200" or "AT1900" in the future, the only words are keep is the "AT", So how can i get the string $b which is after the word "ATxxxx" ? Thanks
Split the string with AT#### using a regex:
$metar_split = preg_split('/AT[0-9]{4}/', $metar);
The first half:
echo trim($metar_split[0]);
The second half (the one you're looking for):
$b = trim($metar_split[1]);
To get the AT#### portion:
preg_match('/AT[0-9]{4}/', $metar, $matches);
$metar_at = $matches[0];
If the position of ATxxxx in the string is always fixed (and the number of characters before it are also fixed), and xxxx always means 4 digits, then you could just go and use substr to select the desired segment of the string, as in:
$part1 = substr($metar, 0, 38);
$part2 = substr($metar, 46);
However, if you are looking at a varying lengths for the rest of the content, yet ATxxxx format is expected, you could have at it with a regular expression along the lines of:
([\w\s\/]+) AT[0-9]{4} ([\w\s\/]+)
This will grab out your two parts, which are seperated by the letters AT and exactly 4 digits. The [\w\s\/]+ part says: "grab me word characters (letters and numbers), white spaces and slash characters at least one, or any number more".
here you go, the answer is attached below:
list($a, $b) = explode('AT', $metar, 2);
//echo $b;
list($c, $d) = explode(' ', $b, 2);
//echo $d;
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}/
I've got a large string that I want to put in an array after each 50 words. I thought about using strsplit to cut, but realised that wont take the words in to consideration, just split when it gets to x char.
I've read about str_word_count but can't work out how to put the two together.
What I've got at the moment is:
$outputArr = str_split($output, 250);
foreach($outputArr as $arOut){
echo $arOut;
echo "<br />";
}
But I want to substitute that to form each item of the array at 50 words instead of 250 characters.
Any help will be much appreciated.
Assuming that str_word_count is sufficient for your needs¹, you can simply call it with 1 as the second parameter and then use array_chunk to group the words in groups of 50:
$words = str_word_count($string, 1);
$chunks = array_chunk($words, 50);
You now have an array of arrays; to join every 50 words together and make it an array of strings you can use
foreach ($chunks as &$chunk) { // important: iterate by reference!
$chunk = implode(' ', $chunk);
}
¹ Most probably it is not. If you want to get what most humans consider acceptable results when processing written language you will have to use preg_split with some suitable regular expression instead.
There's another way:
<?php
$someBigString = <<<SAMPLE
This, actually, is a nice' old'er string, as they said, "divided and conquered".
SAMPLE;
// change this to whatever you need to:
$number_of_words = 7;
$arr = preg_split("#([a-z]+[a-z'-]*(?<!['-]))#i",
$someBigString, $number_of_words + 1, PREG_SPLIT_DELIM_CAPTURE);
$res = implode('', array_slice($arr, 0, $number_of_words * 2));
echo $res;
Demo.
I consider preg_split a better tool (than str_word_count) here. Not because the latter is inflexible (it is not: you can define what symbols can make up a word with its third param), but because preg_split will essentially stop processing the string after getting N items.
The trick, as quite common with this function, is to capture delimiters as well, then use them to reconstruct the string with the first N words (where N is given) AND punctuation marks saved.
(of course, the regex used in my example does not strictly comply to str_word_count locale-dependent behavior. But it still restricts the words to consist of alpha, ' and - symbols, with the latter two not at the beginning and the end of any word).