删除字符串中最后一个方括号之间的文本(但不包括任何其他方括号)

So I have a complicated question that will require an advanced regular expression, which I am trying to write in PHP. I don't have a code snippet, because I really have no idea where to start with this regular expression.

I need to remove some parts of a string, ONLY if that string ends with something like [ABC].

If it starts with [ABC] or if [ABC] is somewhere in the middle, that's fine.

All I need to do is remove the [ABC] if it's at the end of the string. Problem is: the ABC can be any letter/number combination of up to 5 characters.

Some examples:

Hello [ABC] should become Hello

[ABC] Hello should stay [ABC] Hello

[A] Hi [B] should become [A] Hi

[X] Hello [Y] World [Z] should become [X] Hello [Y] World

I managed to remove all content in square brackets (including the brackets), but I have no clue how to make it only remove content + brackets if these brackets are at the very end of the string.

$text= "[X] Hello [Y] World [Z]";
$outputs .= preg_replace('/\[.*?\]/', '', $text);

A $ anchor with a negated character class instead of lazy dot matching pattern will do the job.

\[[^][]*]$

See the regex demo. This seems a bit more generic expression than what you need. You may adjust it for your special case - the ABC can be any letter/number combination of up to 5 characters - as follows:

\[[[:alnum:]]{1,5}]$

See this regex demo.

Pattern details:

  • \[ - a literal [
  • [^][]* - any 0+ chars other than ] and [
    OR
  • [[:alnum:]]{1,5} - 1 to 5 alphanumeric chars
  • ] - a literal ]
  • $ - end of string

See the PHP demo:

$text= "[X] Hello [Y] World [Z]";
$outputs = preg_replace('/\[[[:alnum:]]{1,5}]$/', '', $text);
echo trim($outputs);
// => [X] Hello [Y] World