Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

regex - PHP preg_match_all how to start fething results after a number of first occurencies?

Right now i am working on a PHP script which is fetching all occurencies from a text which have "SizeName": and here is the code for doing this:

preg_match_all('/"SizeName":"([0-9.]+)"/',$str,$matches);

This line of code is fething occurencies from the first time when it finds "SizeName":, but how i can make it start printing data after for example the third time when it finds "SizeName": ?

Is it possible and how i can achieve it ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

preg_match_all('/(?:(?:.*?"SizeName":){2}|G).*?K"SizeName":"([0-9.]+)"/s', $str, $matches);

Demo


(?:             (?# start non-capturing group for alternation)
  (?:           (?# start non-capturing group for repetition)
    .*?         (?# lazily match 0+ characters)
    "SizeName": (?# literally match "SizeName":)
  ){2}          (?# repeat twice)
 |              (?# OR)
  G            (?# start from last match)
)               (?# end alternation)
.*?             (?# lazily match 0+ characters)
K              (?# throw away everything to the left)
"SizeName":     (?# literally match "SizeName":)
"([0-9.]+)"     (?# match the number into capture group 1)

Notes:

  • You don't need to escape ", since it is not a special regex character and you build your PHP String with '.
  • Change the {2} to modify the number of SizeName instances to skip (I wasn't sure if you wanted to skip 3 or start from the 3rd).
  • The s modifier is needed if there are any newline characters between the instances of SizeName, since .*? will not match newline characters without it.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...