1

I'm stuck with php preg_match_all function. Maybe someone wil help me with regexp. Let's assume we have some code:

[a]a[/a]
[s]a[/s]
[b]1[/b]
[b]2[/b]
...
...
[b]n[/b]
[e]a[/e]
[b]8[/b]
[b]9[/b]
...
...
[b]n[/b]

I need to match all that inside [b] tags located between [s] and [e] tags. Any ideas?

middus
  • 9,103
  • 1
  • 31
  • 33

4 Answers4

2

if your structure is exactly the same as above I would personally avoid regex (not a good idea with these fort of languages) and just check the second char of each line. Once you see an s go into consume mode and for each line until you see an e find the first ] and read in everything between that and the next [

smitec
  • 3,049
  • 1
  • 16
  • 12
1

For simplicity use two preg_match calls.

First to retrieve the list you want to inspect /\[s](.+?)\[e]/s.
And then use that result string and match for the contained /\[b](.+?)\[\/b]/s things.

mario
  • 144,265
  • 20
  • 237
  • 291
1

It looks like you are trying to pattern match something that has a treelike structure, essentially like HTML or XML. Any time you find yourself saying "find X located inside matching Y tags" you are going to have this problem.

Trying to do this sort of work with with regular expressions is a Bad Idea.

Here's some info copy/pasted from a different answer of mine for a similar question:

Some references to similar SO posts which will give you an idea of the difficulty you're getting into:

The "Right Thing" to do is to parse your input, maintaining state as you go. This can be as simple as scanning your text and keeping a stack of current tags.

Community
  • 1
  • 1
jwd
  • 10,837
  • 3
  • 43
  • 67
0

Regular expressions alone aren't sufficient to parse XML, and this appears to be a simplified XML language here.

StilesCrisis
  • 15,972
  • 4
  • 39
  • 62