PHP regex cannot get it working?

php, regex

Solution

Try this:

<?php

$reg = "#S\d{1,2}E\d{1,2}#";

$tests = array('S11E22', 'S1E2', 'S11E2', 'S1E22', 'S111E222', 'S111E', 'SE', 'S0E0');

foreach ($tests as $test) {
    echo "Testing $test... ";
    if (preg_match($reg, $test)) {
        echo "Match!";
    } else {
        echo "No Match";
    } 
    echo "\n";
}

Output:

Testing S11E22... Match!
Testing S1E2... Match!
Testing S11E2... Match!
Testing S1E22... Match!
Testing S111E222... No Match
Testing S111E... No Match
Testing SE... No Match
Testing S0E0... Match!

Explanation:

 $reg = "#S\d{1,2}E\d{1,2}#";
          ^ ^  ^  ^ ^  ^
          | |  |  | |  |
    Match S |  |  | |  One or two times
  Match digit  |  | Match a digit
One or two times  Match the letter E

EDIT

Optionally you could have done this with something like

$reg = '#S\d\d?E\d\d?#';

Which is to say, S followed by digit, possibly followed by another digit `?`... so on.

Problem

I am trying to make a regex to match a certain criteria and I cannot get it working how I want it to. My current regex is ``` '/S(?:[0-9]){2}E(?:[0-9]){2}/i' ``` What I would like it to do is match the following criteria An `S` At least one digit `0-9` An optional digit that can be `0-9` An `E` At least one digit `0-9` An optional digit that can be `0-9` I would also like it to match the double numbers over single ones if this is possible, I made up the regex by following tutorials on the internet but think I am missing something. Thanks...

Original source