简体   繁体   中英

preg_match - getting position of regex match in the matched string

So I know if you pass in the flag PREG_OFFSET_CAPTURE you get the index of the regex match in the orginal "haystack", but what if I want the index of the match within the whole match?

Simple example:

Original String: "Have a <1 + 2> day today"

My regular expression /<1 ([+|-]) 2>/

So in the example I am matching whatever symbol is between the 1 and 2. If I did this in preg_match with the PREG_OFFSET_CAPTURE flag, the index for the matched symbol would be 10. I really would like it to return 3 though.

Is there any way to do this?

唯一的方法是将整个模式偏移量(7)减去捕获组偏移量(10):10-7 = 3

$group_offset = $matches[1][1] - $matches[0][1];

You could use a more tricky way by using preg_replace_callback :

$string = 'I have a <1 + 2> day today and a foo <4 - 1> week.';
$match = array();

preg_replace_callback('/<\d+ ([+|-]) \d+>/', function($m)use(&$match){
    $match[] = array($m[0], $m[1], strpos($m[0], $m[1]));
}, $string); // PHP 5.3+ required (anonymous function)
print_r($match);

Output:

Array
(
    [0] => Array
        (
            [0] => <1 + 2>
            [1] => +
            [2] => 3
        )

    [1] => Array
        (
            [0] => <4 - 1>
            [1] => -
            [2] => 3
        )

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM