简体   繁体   English

PHP正则表达式可识别多个令牌

[英]PHP regex to identify multiple tokens

I need to create a regex in PHP that will identify the following tokens in a section of text: 我需要在PHP中创建一个正则表达式,该正则表达式将在文本的一部分中标识以下标记:

[video:1]
[video:2]

The code I'm using is 我正在使用的代码是

preg_match("/\[video:[12]{1}\]/", $text, $matches);

with the idea that I can have one character of either 1 or 2 after '[video:' and then ']'. 我可以在[[video:]然后是[]]之后使用1或2个字符。 The problem I'm having is that it won't identify the second token if there are two of them in the text. 我遇到的问题是,如果文本中有两个标记,它将无法识别第二个标记。 It will identify either one if it is the first one, but not the second one if both are in the text. 如果它是第一个,它将标识一个,如果两者都在文本中,它将标识第二个。

How can I identify both tokens in my section of text? 如何在我的文字部分中识别两个标记?

Thanks. 谢谢。

You need to use preg_match_all() to to a global search and capture. 您需要使用preg_match_all()进行全局搜索和捕获。

Also be sure to properly escape regular expression syntax when you need to match literal characters. 另外,在需要匹配文字字符时,请确保正确转义正则表达式语法。

/\[video:[12]\]/

Note: I also removed the quantifier as it is unnecessary since you are just matching one 1 or 2 . 注意:我也删除了量词,因为您只匹配12 ,所以不必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM