How to skip first regex match?

故事扮演 提交于 2019-11-29 16:47:52

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.

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.)

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

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 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!