while ($test =~ m!\[img\]((?:[^\[]+|\[[^i]|\[i[^m]|\[im[^g]|...)+\[\/img\]!g) { print "$1 \n"; }