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

寵の児 提交于 2019-12-12 06:34:53

问题


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 ?


回答1:


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.



回答2:


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'.



来源:https://stackoverflow.com/questions/25171406/php-preg-match-all-how-to-start-fething-results-after-a-number-of-first-occurenc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!