skip to Main Content
$string='letters=ABCD';

We want to match "letters=" and letter B or C. The letter in string may input as:

  • B
  • C
  • BC
  • CB
    How to filter out A and D and output result as letters=BC ?

preg_match('/(letters=([BC]+))/', $string,$matches);

  • This match if letter in string start letter B or C and can filter out D
  • not work when letter start other letter

preg_match('/<FORMAT=[A-Z]+[BIU]+/', $string,$matches);

  • The result not filter out A in result

2

Answers


  1. If I understand the problem correctly you can replace every match of the following regular expression with an empty string.

    ^.*'(?=(?:letters|LETTERS)=[A-Z]+';$)|[AD-Z](?!.*=)|';$
    

    Demo

    This expression can be broken down as follows.

    ^             match beginning of string
    .*            match zero or more chars other than line terminators
    '             match literal
    (?=           begin a positive lookahead
      (?:         begin a non-capture group
        letters   match literal
      |           or
        LETTERS   match literal
      )           end the non-capture group
      =           match literal
      [A-Z]+      match one or more uppercase letters
      ';          match literal
      $           match end of string
    )             end the positive lookahead 
    |             or
    [AD-Z]        match a capital letter other than 'B' or 'C'
    (?!           begin a negative lookahead
      .*          match zero or more chars other than line terminators
      =           match literal
    )             end the negative lookahead
    |             or
    ';            match literal
    $             match the end of the string
    
    Login or Signup to reply.
  2. You could try:

    (?:^letters=|G(?!^))[BC]*K[AD-Z]+
    

    See an online demo


    • (?:^letters=|G(?!^)) – Non-capture group to match the start of the input as literally ‘letters=’ or assert position at end of previous match but negate start of string;
    • [BC]* – 0+ times the letters ‘B’ or ‘C’;
    • K – Reset starting point of reported match;
    • [AD-Z]+ – Match 1+ uppercase letters in range ‘AD-Z’.

    Replace with empty string:

    echo preg_replace('/(?:^letters=|G(?!^))[BC]*K[AD-Z]+/', '', $string);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search