简体   繁体   中英

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:

[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 ']'. 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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