How to skip first regex match?

后端 未结 4 1983
伪装坚强ぢ
伪装坚强ぢ 2020-12-22 01:55

Is there anyway to skip the first match when using regex and php.

Or is there some way of achieveing this using str_replace.

Thanks

UPDATE

相关标签:
4条回答
  • 2020-12-22 02:03
    preg_replace('/((?:^.*?\btest\b)?.*?)\btest\b/', '$1', $string);
    

    The idea is to match and capture whatever precedes each match, and plug it back in. (?:^.*?test)? causes the first instance of test to be included in the capture. (All the \bs are to avoid partial-word matches, like the test in smartest or testify.)

    0 讨论(0)
  • 2020-12-22 02:15

    assume 'blah' is your regex pattern, blah(blah) will match and capture the second one

    0 讨论(0)
  • 2020-12-22 02:22

    Late answer but it might be usefull to people.

    $string = "This is a test string to test something with the word test and replacing test";
    $replace = "test";
    $tmp = explode($replace, $string);
    $tmp[0] .= $replace;
    $newString = implode('', $tmp);
    echo $newString; // Output: This is a test string to something with the word and replacing 
    
    0 讨论(0)
  • 2020-12-22 02:23

    Easy PHP way:

    <?php
        $pattern = "/an/i";
        $text = "banANA";
        preg_match($pattern, $text, $matches, PREG_OFFSET_CAPTURE);
        preg_match($pattern, $text, $matches, 0, $matches[0][1]);
        echo $matches[0];
    ?>
    

    will give you "AN".

    UPDATE: Didn't know it was a replace. Try this:

    <?php
        $toRemove = 'test';
        $string = 'This is a test string to test to removing the word test';
        preg_match("/$toRemove/", $string, $matches, PREG_OFFSET_CAPTURE);
        $newString = preg_replace("/$toRemove/", "", $string);
        $newString = substr_replace($newString, $matches[0][0], $matches[0][1], 0);
        echo $newString;
    ?>
    

    Find the first match and remember where it was, then delete everything, then put whatever was in the first spot back in.

    0 讨论(0)
提交回复
热议问题