user3810164
user3810164

Reputation: 11

Get a valid match for a regular expression

Hej,

I'm doing a project which involves a quiz. Multiple choice and text input as answers. For checking the text input answers there is a RegEx. For instance:

What is the name of this operation: 3 + 5. Possible answers: Addition, addition, Plus, plus, Sum, sum, + RegEx: /^((A|a)ddition|(P|p)lus|(S|s)um|\+)$/

So far so good. But now I want to display a valid answer if someone answers incorrectly. I don't want to redundantly save this in the database.

So my question is: Is there a php-function that gives me a valid string for any given RegEx?

Like: echo 'Your answer is wrong, '.valid_pattern($theRegEx).' would have been better.';

Thanks in advance

Upvotes: 1

Views: 78

Answers (1)

Federico Piazza
Federico Piazza

Reputation: 31045

If you want to generate sample data using a regex you can check at ReverseRegex php project.

https://github.com/icomefromthenet/ReverseRegex

Here you have an example form its page:

use ReverseRegex\Lexer;
use ReverseRegex\Random\SimpleRandom;
use ReverseRegex\Parser;
use ReverseRegex\Generator\Scope;

# load composer
require "vendor/autoload.php";

$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;

Will generate:

jmceohykoa
aclohnotga
jqegzuklcv
ixdbpbgpkl
kcyrxqqfyw
jcxsjrtrqb
kvaczmawlz
itwrowxfxh
auinmymonl
dujyzuhoag
vaygybwkfm

I haven't tried it but I think it is useful for your need.

Upvotes: 1

Related Questions