您忘记在正则表达式中包含下划线:
$reg = "/\[[A-Z]+[0-9A-Z]*/"; // => this matches [TAG and not [TAG_123
此外,您需要删除+
from [A-Z]
,因为它只需要一次。
<?php
$content = " some text [TAG_123] and other text";
$regs="/\[[A-Z][0-9A-Z]*/";
preg_match($regs, $content, $matches);
print_r($matches);
$regs="/\[[A-Z][0-9A-Z_]*/";
preg_match($regs, $content, $matches);
print_r($matches);
$regs="/\[[A-Z][0-9A-Z_]*\]/";
preg_match($regs, $content, $matches);
print_r($matches);
结果
Array ( [0] => [TAG )
Array ( [0] => [TAG_123 )
Array ( [0] => [TAG_123] )