Regular expression that finds [abc] but not [;;abc]

Viewed 198

It's so late, I can't quite get it.

My text looks like this:

 This is a [;;Text] and I want to match [center]everything without ;;[/center]

I use this to transform to HTML:

 return preg_replace('/\[(.+)\]/U', '<$1>', $text);

And I thought the pattern /\[[^;{2}](.+)\]/U should do the trick but it does not work.

4 Answers

You can for example match [ and an optional / followed by word characters till the closing ]

Note that you don't need the /U flag in this case to make the quantifiers lazy.

\[/?\w+]

$text = ' This is a [;;Text] and I want to match [center]everything without ;;[/center]';
$result = preg_replace('/\[(\/?\w+)]/', "<$1>", $text);
echo $result;

Output

This is a [;;Text] and I want to match <center>everything without ;;</center>

Regex demo


For a more specific match, you can exclude matching ;; after the [ and match all characters except [ and ] using a negated character class.

\[(?!;;)([^][]*)]

Regex demo

I found the following pattern: \[(?<!\;\;)([\w\/]+?)\]

A link to the demonstration: https://regex101.com/r/Htd32j/1

Please be aware that it only matches in that specific case, if you want any tags with spaces or other special characters it won't work and might need some modification.

The regex I came up with to match this pattern is pretty straight-forward:

[[][A-Za-z0-9]*[]]

To break it down into smaller parts for understanding:

[[] begins with "["

[A-Za-z0-9]* contains one or more alphabet or numeric character
          
[]] ends with "]"

This will match [center] but not [/center] or [;;Text] because they have special characters and the regex is looking for only alphabet and numeric.


Edit: if you want to match every character except ";" then you can use this:

[[][^;]*[]]

Which follows very similar logic:

[[] begins with "["

[^;]* one or more character that is not ";"

[]] ends with "]"

Which will match [center] and [/center] but not [;;Text]

Related