I am searching for PHP component that generates random string from regex. I've searched through this forum, but found only PERL etc. solutions (Random string that matches a regexp). Is there such an open source class?
In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers. $exp = "/w3schools/i"; In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.
Regular expressions are useful in search and replace operations. The typical use case is to look for a sub-string that matches a pattern and replace it with something else. Most APIs using regular expressions allow you to reference capture groups from the search pattern in the replacement string.
A library called ReverseRegex can be found here.
As of January 2014 the project seems not to be dead.
Usage seems to be as simple as
$lexer = new Lexer('[a-z]{10}');
$gen = new SimpleRandom(10007);
$result = '';
$parser = new Parser($lexer,new Scope(),new Scope());
$parser->parse()->getResult()->generate($result,$gen);
echo $result;
Give it a regex, give it a random seed and generate your string.
The above example, taken from the github-site, generates a ten character long random string consisting only of letters.
(originally found in this answer)
I'm not familiar I wasn't (until now) familiar with any php libraries that can do this, and converting something like xeger would be a tremendous undertaking.
Instead, you could simply do something like this:
function random($length)
{
$random_string = "";
$valid_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}\\|";
$num_valid_chars = strlen($valid_chars);
for ($i = 0; $i < $length; $i++)
{
$random_pick = mt_rand(1, $num_valid_chars);
$random_char = $valid_chars[$random_pick-1];
$random_string .= $random_char;
}
return $random_string;
}
echo random(20); //generates a random string, 20 characters long.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With