David David - 29 days ago 6
PHP Question

regexp in PHP: may contain, but doesn't have to

This is my code:

<?php
if(preg_match('"^[0-9 ]*/[0-9 ]*$"', "1 23/45 67 89")) {
echo "Match pattern!";
} else {
echo "Doesn't match pattern!";
}
?>


How to change to: String may contain
/
but doesn't have to contain
/
to match pattern?

Examples:

"1 23/45 67 89"; match pattern
"1 2345 67 89"; match pattern
"1 23/45 /67 89" doesn't match pattern (because of two `/`)
"1 23/45 67A 89" doesn't match pattern (because of unhallowed character `A`)

Answer

This should work, then:

<?php
if(preg_match('"(^[0-9 ]*\/[0-9 ]*$)|(^[0-9 ]*$)"', "1 23/45 67 89")) {
    echo "Match pattern!";
} else {
    echo "Doesn't match pattern!";
}
?>