Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the position of a Regex match in a string? [duplicate]

Tags:

string

regex

php

I know how to use preg_match and preg_match_all to find the actual matches of regex patterns in a given string, but the function that I am writing not only needs the text of the matches, but to be able to traverse the string AROUND the matches...

Therefore, I need to know the position of the match in the string, based on a regex pattern.

I can't seem to find a function similar to strpos() that allows regex...any ideas?

like image 871
johnnietheblack Avatar asked Mar 05 '12 17:03

johnnietheblack


People also ask

Which function returns the part of the string where there was a match?

The search() function searches the string for a match, and returns a Match object if there is a match.

What does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.

How do I find a character in a string in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


2 Answers

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.

like image 67
Linus Kleen Avatar answered Sep 29 '22 16:09

Linus Kleen


preg_match has an optional flag, PREG_OFFSET_CAPTURE, that records the string position of the match's occurence in the original 'haystack'. See the 'flags' section: http://php.net/preg_match

like image 28
Marc B Avatar answered Sep 29 '22 16:09

Marc B