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.

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
  • 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
    Feb 9, 2012 at 4:37
  • @John $str is the subject of the search
    – Phil
    Feb 9, 2012 at 4:47

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.