0

说我有类似的东西:

$content = " some text [TAG_123] and other text";

我想匹配[TAG_123]

更准确地说:[后跟一个大写字母A-Z,然后是零或几个0-9A-Z_,然后是].

我试过了 :

$reg = "/\[[A-Z]+[0-9A-Z_]*/"; // => this match [TAG_123

$reg = "/\[[A-Z]+[0-9A-Z_]*\]/"; // => this doesn't work ???
4

2 回答 2

0
  • [A-Z]: 1 个字母,A-Z
  • [A-Z0-9_]*: 0 或更多, A-Z,0-9_
  • \[and \]: 字面上匹配[and]

$content = " some text [TAG_123] and other text";
if (preg_match('/\[[A-Z][0-9A-Z_]*\]/', $content, $matches)) {
    print_r($matches); // $matches[0] includes [TAG_123]
}
于 2013-04-24T14:56:17.007 回答
0

您忘记在正则表达式中包含下划线:

$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] ) 
于 2013-04-24T14:58:45.677 回答