Bert
Bert

Reputation: 855

regex preg_match loop through different terms

I want to go through a string and match on different terms, but can't get it working. I want to match on {tab ...} en {media ...} and handle them differently.

If I only match on one, it works:

while ($do = preg_match("/{tab(.*?)}/", $description, $match, PREG_OFFSET_CAPTURE, $offset)){

But when I add the media tag, it doesn't work anymore. This is what I use now:

while ($do = preg_match("(/{tab(.*?)}/|/{media(.*?)}/)", $description, $match, PREG_OFFSET_CAPTURE, $offset)){
...
}

Upvotes: 0

Views: 77

Answers (2)

revo
revo

Reputation: 48741

This is enough:

{tab(.*?)}|{media(.*?)}

No need for that additional slashes. also you should use preg_match_all if you have more consequences of them in your string.

preg_match_all("/{tab(.*?)}|{media(.*?)}/", $description, $match, PREG_OFFSET_CAPTURE, $offset))

Upvotes: 1

Jerry
Jerry

Reputation: 71578

You seem to be confusing the regex delimiters and the way parens are used. Try this:

"/{tab(.*?)}|{media(.*?)}/"
 ^                       ^

Notice that the delimiters remain where they were. You might even try something like this:

"/{(?:tab|media)(.*?)}/"

I'm not sure what you meant by handle them differently, but most of the time, that means that you should keep them in separate regexes.

Upvotes: 1

Related Questions