Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP component that generares random string from regex [closed]

Tags:

regex

php

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?

like image 522
Michal Avatar asked Jan 09 '14 20:01

Michal


People also ask

How does regex work PHP?

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.

When to use regexp?

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.


2 Answers

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)

like image 171
KeyNone Avatar answered Oct 27 '22 21:10

KeyNone


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.
like image 4
brandonscript Avatar answered Oct 27 '22 20:10

brandonscript