0

次のようなものがあるとします。

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

合わせたい[TAG_123]

より正確に言うと[、1 つの大文字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-Z0-9または_
  • \[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 に答える