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 ... ] ... ... ';