0

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm not sure I understand your reference to escaping, since what you put above matches what I had (without the removed {1} quantifer), but this worked. Thanks.
You're welcome. Your original post was not escaping. Felix Kling added them after my answer.
Just FYI, the backslashes were there along. They just weren't visible before Felix applied code formatting. This kind of thing is why I usually initiate an edit on a question before I try to answer it, to make sure I'm seeing what the author wants me to see.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.