1

This code prints "Got match" if the string can be matched in the /$reg/. Is is possible for me not just to match but display all the possible strings from that regular expression. Like for example my regular expression is "(a|b)*" possible strings are aaaa, abbb, bbbb, bbbaa, etc. I want to print all of those with the maximum length 5.

if(isset($_POST['calc'])){
$reg = $_POST['regex']; 
$str = $_POST['str'];

if (preg_match("/$reg/", $str)) 
{
    echo "Got match!";
}

else 
{
echo "String not valid";
}
}

?>

2 Answers 2

3
unset($matches);
if (preg_match_all("/$reg/", $str, $matches, PREG_PATTERN_ORDER)) 
{
    var_dump($matches[0]);
}

See the documentation.

Sign up to request clarification or add additional context in comments.

Comments

0

Use preg_match_all()

if (preg_match_all('/\b[ab]{1,5}\b/', $str, $matches)) {
    echo implode(', ', $matches[0]);
}

This finds all strings of sequential "a" or "b" characters up to a maximum length of 5.

2 Comments

Thank you sir, can I ask a question? If this finds all strings of sequential "a" or "b" how come there is still an string in the parameters ($str). what string should I put there?
@John $str is the subject of the search

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.