RegEx匹配balise []与A Z0-9内部

时间:2013-04-24 14:49:54

标签: php regex

说我有类似的东西:

$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 ???

2 个答案:

答案 0 :(得分:0)

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

$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]
}

答案 1 :(得分:0)

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

$reg = "/\[[A-Z]+[0-9A-Z]*/"; // => this matches [TAG and not [TAG_123

此外,您需要从+中移除[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] )