skip to Main Content

I’m trying to write regular expression for the next pharse "AE/ME 5101" or "AWE/ME 5101" or or "any text or no text AWE/MERL 5101 any text or no text"

I need to catch "AWE/MERL 5101" or "AE/ME 5101" or "AWE/ME 5101" in the string or the string can have only this pharse. Anyway i need extract it. I’m trying to use /[A-Z]{1-4}/[A-Z]{1-4}/ but it doesn’t work

Any help

2

Answers


  1. Chosen as BEST ANSWER
    $pattern = '/^[A-Z]+/[A-Z]+(?: [A-Z]+)? d+$/';
    
    $strings = [
        "AE/ME 5101",
        "ECE/CS 673",
        "RBE/CS 526",
        "PY/RE 716",
        "RBE/CST 5265"
    ];
    
    foreach ($strings as $string) {
        if (preg_match($pattern, $string)) {
            echo "$string is a valid match.<br>";
        } else {
            echo "$string is not a valid match.<br>";
        }
    }
    

  2. I suggest you use the possible variations of your string inside a bracket, and to avoid collisions use another character – suggested here ~ – as the pattern delimiter:

    $pattern = '~(AE/ME|AWE/ME|AWE/MERL) 5101~';
    

    Check:

    $matches = [];
    var_dump(preg_match($pattern, 'foo AWE/ME 5101 bar', $matches));
    

    Result:

    int(1)
    

    If you need the actual text that matched, this is available in $matches[0]

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search