php preg_match return position of last match

前端 未结 4 546
南旧
南旧 2021-01-11 17:32

With

preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE); 

is it possible to search a string in reverse? ie. return the position

4条回答
  •  轮回少年
    2021-01-11 18:18

    "Greedy" is the key word here. * is by default greedy *? limits greediness to the bare minimum.

    So the solution is to use the combination, e.g. (searching for last period followed by a whitespace):

    /^.*\.\s(.*?)$/s
    
    • ^ is the beginning of text
    • .* eats as much as it can, including matching patterns
    • \.\s is the period followed by a whitespace (what I am looking for)
    • (.*?) eats as little as possible. Capture group () so I could address it as a match group.
    • $ end of text
    • s - makes sure newlines are ignored (not treated as $ and ^, . dot matches newline)

提交回复
热议问题