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
124 views
in Technique[技术] by (71.8m points)

php - How to get the position of a Regex match in a string?


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

1 Answer

0 votes
by (71.8m points)

You can use the flag PREG_OFFSET_CAPTURE for that:

preg_match('/bar/', 'Foobar', $matches, PREG_OFFSET_CAPTURE);
var_export($matches);

Result is:

array (
  0 => 
  array (
    0 => 'bar',
    1 => 3,     // <-- the string offset of the match
  ),
)

In a previous version, this answer included a capture group in the regular expression (preg_match('/(bar)/', ...)). As evident in the first few comments, this was confusing to some and has since been edited out by @Mikkel. Please ignore these comments.


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

...