PHP preg_match_all如何在多次首次出现后开始获取结果?

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 ?

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.

Use a combination of strpos and the preg_match_all's offset. Basically, start your search after the 2nd occurrence of the string.

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

I'm hard coding the number 8 because that is the string length of 'SizeName'.