1

Please read part 1 of this question:-

Need Help In Regex, substring between two brackets

$result = '';
$str = ' ... [ ... SUB_STRING_TO_BE_SEARCHED ... ] ... [ ... / ... SUB_STRING_TO_BE_SEARCHED ... ] ... [ ... THIS_SHOULD_NOT_GET_SELECTED ... ]';
$sub_str = '';
if( preg_match('#\[.*?'.$sub_str.'.*?\]#' , $str) ) {
    if ( preg_match( REGEX_2 , $str ) ) {
        $result = preg_replace( REGEX_3 , '', $str);
    } else {
        $result = preg_replace('#\[.*?'.$sub_str.'.*?\]#', '', $str);
    }
}

$result should be:-

$result = " ...  ... [ ... THIS_SHOULD_NOT_GET_SELECTED ... ]";

However, for $str_2:-

$str_2 = ' ... [ ... SUB_STRING_TO_BE_SEARCHED ... ] ... [ ... THIS_SHOULD_NOT_GET_SELECTED ... ]';

the $result should also remain:-

$result = " ...  ... [ ... THIS_SHOULD_NOT_GET_SELECTED ... ]";

Explanation:-

Step 1: Ok, from previous question I can easily get this string:-

[ ... THIS_SHOULD_NOT_GET_SELECTED ... ]

Step 2:- REGEX_2 should check if this exists:-

[ ... / ... THIS_SHOULD_NOT_GET_SELECTED ... ]

(notice a forward slash, let's assume that it will appear only once between the THIS_SHOULD_NOT_GET_SELECTED and the left bracket [.)

Step 3:- If REGEX_2 is found then REGEX_3 should select this substring:-

[ ... SUB_STRING_TO_BE_SEARCHED ... ] ... [ ... / ... SUB_STRING_TO_BE_SEARCHED ... ]

Another Examples:-

$str_3 = ' ... [ ... AA ... ] ... [ ... / ... AA ... ] ... [ ... B ... ] ... [ ... AA ... ] ... [ ... / ... AA ... ] ... [ ... AA ... ]';
$substring_3 = 'AA'
$result = ' ...  ... [ ... B ... ] ...  ... ';

1 Answer 1

2

I would opt for negated classes instead of .*?, and in case the substring_3 is AA, then:

\[[^]]*?AA[^]]*?\](?:[^[]*\[[^]]*?/[^]]*?AA[^]]*?\])?

In:

$result = preg_replace('#\[[^]]*?'.$sub_str.'[^]]*?\](?:[^[]*\[[^]]*?/[^]]*?'.$sub_str.'[^]]*?\])?#', '', $str);

regex101 demo


\[          # Match [
  [^]]*?    # Any number of non ]
  AA        # The substr
  [^]]*?    # Any number of non ]
\]          # Match ]
(?:
  [^[]*     # Any number of non [
  \[        # Match [
    [^]]*?  # Any number of non ]
    /       # Match /
    [^]]*?  # Any number of non ]
    AA      # The substr
    [^]]*?  # Any number of non ]
  \]        # Match ]
)?          # Make this group optional
Sign up to request clarification or add additional context in comments.

1 Comment

@OmarTariq Well, if you find something like that beautiful... :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.